Host header injection: when your application takes its own name from the request
Every request tells the server which site it is asking for, and whoever sends the request writes that name.
Host header injection is what follows when an application uses the name to build its own links: on a page, in a redirect or in a password reset email. This guide covers who sets the Host header, how a proxy changes what the application sees, how six frameworks and two web servers decide their own name, the four controls, and a trusted-host test pack with a lab you can run on your own computer.
In this guide
Trusted-host test pack and local lab
Part 1 is a test pack with four rows, absolute URL generation, password reset links, cache variation and proxy forwarding: the request to send, what to observe, the result to expect after remediation and the source behind it, with spaces for your own results. Parts 2 and 3 are an illustration you can run with Node.js and no installs: an invented booking application, a reverse proxy and a cache, each in a careless and a careful version, with seven cases and seven regression tests, and every output copied from one recorded run on Node.js 26.0.0.
How to use itHide the instructions
Part 4 lists the same tests for your own application.
host-header-injection.txt
Introduction21 lines
Part 1: The trusted-host test pack71 lines
Part 2: The lab files689 lines
Part 3: The recorded run435 lines
Part 4: The same tests on your own application21 lines
Whole template1,261 lines
TRUSTED-HOST TEST PACK AND LOCAL LAB
ILLUSTRATION ONLY. Part 1 is a test pack for your own application. Parts 2 and 3 are a lab written for this page and run on one computer: an invented booking application, Tideline Tours, a small reverse proxy and a small cache, each in a careless and a careful version. The application, its customer, its host names and its messages are invented, and nothing in the lab is a client's system or a client's result. The lab shows a pattern. It does not show how any real framework, proxy, load balancer, cache or CDN behaves. Use what it teaches only on systems you own or are authorised in writing to test.
WHAT THE LAB NEEDS
Node.js. Apart from each other, the lab files import only node:assert/strict, node:http, node:net and node:test, and the lab installs no packages. The run in Part 3 was recorded on macOS with Node.js 26.0.0, the only version and the only system it was run on. Timings differ from run to run. Steps 2 and 4 set the LAB_VERSION environment variable in front of the command, which is how the run was made, in bash on macOS. In another shell, set the variable the way that shell does.
WHAT THE LAB DOES NOT DO
Every server in the lab listens on 127.0.0.1, on a port the system picks, and no port is printed. The lab client opens every connection to the literal address 127.0.0.1 and writes each request as text. It sends its three host names only as header values inside requests and never connects to one. The application sends no email: a reset message is an entry in a list in memory, which the lab prints. The lab writes nothing to disk. Each command starts its servers inside its own process and stops them before it ends.
THE NAMES
bookings.tideline.example the name in the configured origin, https://bookings.tideline.example
tideline-tours.example a second name the application also serves
other-host.test stands for any name the application does not serve
All three are invented. They sit under .example and .test, two of the four top level names that RFC 2606 reserves.
WHAT IS HERE
Part 1 The trusted-host test pack: four rows to fill in for your own application
Part 2 The lab files: ten files
Part 3 The recorded run: four commands and what each printed
Part 4 The same tests on your own application
================================================================
PART 1: THE TRUSTED-HOST TEST PACK
================================================================
Before you start
Run these rows only against an application you own or are authorised in writing to test, in a staging or test environment. Use a test account whose mailbox you control: rows 2 and 4 make the application send a reset message, and it has to come to you. Never request a reset for a real person's account. Write down the configured origin you expect, scheme and host together, before you send anything. For the other host, use an invented name such as one under .test. Do not use a real domain you do not control: if the application does build a link from it, that link points at someone else's site.
Words used in the rows
REAL-HOST the host name of your test environment, as it appears in its address
SECOND-HOST another name your application also answers to, if it has one
OTHER-HOST an invented name your application does not serve, such as other-host.test
CONFIGURED ORIGIN the one origin you expect in every generated link, such as https://bookings.tideline.example
Sending the requests
Each request goes to your test server's address with the Host header set to the name in the row. Use an HTTP client that lets you set the Host header separately from the address it connects to. lab-client.mjs in Part 2 shows the idea: it connects to an address and writes the Host header itself.
ROW 1: ABSOLUTE URL GENERATION
Lab cases
1A and 1B
Request to send
A page of yours that contains a full address (a canonical tag, a social tag, a link or a redirect), requested with the Host header set to OTHER-HOST. Then the same request with SECOND-HOST.
What to observe
The status, and the origin of every full address in the response: in the body, in the Location header and in any other header that carries a URL.
Expected after remediation
OTHER-HOST: a refusal, with nothing in it built from the name. SECOND-HOST: the page, with CONFIGURED ORIGIN in every full address.
Behind the expectation
WSTG v4.2, WSTG-INPV-17: initial testing is as simple as supplying another domain into the Host header field, and in the simplest case this may cause a 302 redirect to the supplied domain. That generated addresses come from one configured origin is this page's advice, in line with PortSwigger's: specify the current domain in a configuration file and refer to that value instead of the Host header.
Before: ____________ After: ____________ Date: ____________ Evidence kept: ____________
ROW 2: PASSWORD RESET LINKS
Lab cases
2A and 2B
Request to send
The forgotten-password request for your test account, with the Host header set to OTHER-HOST. Then with SECOND-HOST. One request each.
What to observe
The status, and the origin of the link in the message that arrives in the test mailbox. If nothing arrives, record that.
Expected after remediation
OTHER-HOST: a refusal and no message. SECOND-HOST: a message whose link starts with CONFIGURED ORIGIN and uses HTTPS.
Behind the expectation
OWASP Forgot Password Cheat Sheet: do not rely on the Host header while creating the reset URLs; the URL should either be hard-coded or validated against a list of trusted domains; ensure that the URL is using HTTPS. WSTG v4.2, WSTG-INPV-17, under Password Reset Poisoning.
Before: ____________ After: ____________ Date: ____________ Evidence kept: ____________
ROW 3: CACHE VARIATION
Lab case
3
Request to send
On a path no visitor uses, through your cache or CDN: the page with the Host header set to OTHER-HOST, then the same path with REAL-HOST, then with SECOND-HOST.
What to observe
For each request: the status, the cache status header your product returns, and the origin of the full addresses in the page. Then read how your cache key is defined and whether the host is part of it.
Expected after remediation
No request is served a page that was built for a different Host header. One of three things makes that true: the first request is refused and its reply is not stored, each name has its own entry, or the page holds only CONFIGURED ORIGIN whichever name asked for it.
Behind the expectation
RFC 9111 section 2: the cache key is composed from, at a minimum, the request method and target URI. WSTG v4.2, WSTG-INPV-17, under Web Cache Poisoning. That a page built from the Host header is not stored under a key that leaves the host out is this page's advice.
Before: ____________ After: ____________ Date: ____________ Evidence kept: ____________
ROW 4: PROXY FORWARDING
Lab cases
4A and 4B
Request to send
Through your reverse proxy or load balancer: the forgotten-password request for your test account with the Host header set to OTHER-HOST. Then the same request with REAL-HOST in the Host header and one more header, X-Forwarded-Host: OTHER-HOST. Repeat the second request with each forwarded header your proxy or framework documents, such as Forwarded: host=OTHER-HOST.
What to observe
Which layer answered. The Host and forwarded host headers the application received, from a temporary log line in the test environment. The origin of the link in the message that arrives, if one does.
Expected after remediation
OTHER-HOST: the proxy refuses and the application receives nothing. REAL-HOST with a client-written forwarded header: the application receives only the value the proxy wrote, and the link starts with CONFIGURED ORIGIN.
Behind the expectation
RFC 7239 section 8.1: the Forwarded header field cannot be relied upon to be correct, as it may be modified by every node on the way to the server, including the client making the request. Express's guide to running behind proxies, in a warning for trust proxy set to true: it is important to ensure that the last reverse proxy trusted is removing or overwriting all of X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto, otherwise it may be possible for the client to provide any value. WSTG v4.2, WSTG-INPV-17, under X-Forwarded Host Header Bypass. That the proxy refuses unknown names itself is this page's advice, in line with Django's deployment checklist.
Before: ____________ After: ____________ Date: ____________ Evidence kept: ____________
TWO MORE REQUESTS WORTH SENDING
One request with no Host header, and one with two. RFC 9112 section 3.2: a server MUST respond with a 400 (Bad Request) status code to any HTTP/1.1 request message that lacks a Host header field and to any request message that contains more than one Host header field line. The lab does not run these two.
================================================================
PART 2: THE LAB FILES
================================================================
Make an empty folder named trusted-host-lab, save the ten files below into it under the names shown, and run the commands in Part 3 from that folder. In each of app.mjs, proxy.mjs and cache.mjs, a comment that starts CARELESS or CAREFUL marks the lines that differ between the two versions.
================================================================
FILE 1 OF 10: lab-settings.mjs
================================================================
// lab-settings.mjs: names, paths and small helpers. Every other lab file
// except forward.mjs imports from this one. Illustration only. Tideline
// Tours, its host names and its one customer are invented for this lab.
// The one configured origin. The careful application starts every link with it.
export const CANONICAL_ORIGIN = 'https://bookings.tideline.example'
export const CANONICAL_HOST = 'bookings.tideline.example'
// A second name the invented business also serves: an older address that
// still points at the application.
export const SECOND_SERVED_HOST = 'tideline-tours.example'
// The allow-list. The careful application and the careful proxy each check
// the Host header against it.
export const SERVED_HOSTS = [CANONICAL_HOST, SECOND_SERVED_HOST]
// Stands for any name the application does not serve.
export const OTHER_HOST = 'other-host.test'
export const TOUR_PATH = '/tours/sunrise-paddle'
export const RESET_PATH = '/password-reset'
export const LAB_ACCOUNT_EMAIL = 'alex@customer.example'
export const VERSIONS = ['careless', 'careful']
export const REFUSAL_STATUS = 421
export const REFUSAL_TEXT = 'Misdirected Request: this server does not serve that host name.'
export const NEWLINE = String.fromCharCode(10)
export const CRLF = String.fromCharCode(13, 10)
// Lower-cases a Host header value and drops everything from the first colon,
// so "Bookings.Tideline.Example:443" becomes "bookings.tideline.example".
export function readHostName(headerValue) {
return String(headerValue || '').toLowerCase().split(':')[0]
}
// True when the Host header value, read that way, is on the allow-list.
export function isServedHost(headerValue) {
return SERVED_HOSTS.includes(readHostName(headerValue))
}
const ORIGIN_PATTERN = /https:[/][/][a-z0-9.:-]+/gi
// Lists each different "https://name" found in a piece of text, in the order
// it first appears.
export function listOrigins(text) {
const found = String(text).match(ORIGIN_PATTERN) || []
return Array.from(new Set(found))
}
================================================================
FILE 2 OF 10: forward.mjs
================================================================
// forward.mjs: helpers for reading a body, sending a request on to a lab
// server and writing a reply. The proxy and the cache import all four. The
// application imports two, readStream and sendPlainText.
// Every onward request goes to the literal address 127.0.0.1.
import http from 'node:http'
export function readStream(stream) {
return new Promise(function (resolve, reject) {
let text = ''
stream.setEncoding('utf8')
stream.on('data', function (chunk) { text += chunk })
stream.on('end', function () { resolve(text) })
stream.on('error', reject)
})
}
// Sends the request on with the headers it is given and resolves with the
// status, headers and body of the reply.
export function forwardRequest(port, request, headers, body) {
return new Promise(function (resolve, reject) {
const options = { host: '127.0.0.1', port: port, method: request.method, path: request.url, headers: headers, agent: false }
const outgoing = http.request(options, function (incoming) {
readStream(incoming).then(function (replyBody) {
resolve({ status: incoming.statusCode, headers: incoming.headers, body: replyBody })
}, reject)
})
outgoing.on('error', reject)
outgoing.end(body)
})
}
// Writes a reply received from another lab server, adding any extra headers.
export function sendReply(response, reply, extraHeaders) {
response.writeHead(reply.status, Object.assign({}, reply.headers, extraHeaders))
response.end(reply.body)
}
// Writes a short plain-text answer marked no-store.
export function sendPlainText(response, status, text) {
response.writeHead(status, {
'content-type': 'text/plain',
'content-length': Buffer.byteLength(text),
'cache-control': 'no-store',
})
response.end(text)
}
================================================================
FILE 3 OF 10: app.mjs
================================================================
// app.mjs: the invented application, Tideline Tours, in two versions.
// Illustration only. It shows a pattern, not how any real framework behaves.
// Everything it keeps is in memory: an outbox that holds the reset messages,
// a list of the Host and X-Forwarded-Host headers of each request, and a
// counter for reset tokens. It builds the tour page each time one is
// requested, and the address of its one customer account is a constant in
// lab-settings.mjs. It sends no email.
import http from 'node:http'
import { readStream, sendPlainText } from './forward.mjs'
import {
CANONICAL_ORIGIN, LAB_ACCOUNT_EMAIL, NEWLINE, REFUSAL_STATUS, REFUSAL_TEXT, RESET_PATH, TOUR_PATH, isServedHost,
} from './lab-settings.mjs'
const RESET_REPLY = 'If that address has an account, a reset link is on its way.'
// CARELESS: the application takes its own name from the request. It uses the
// first X-Forwarded-Host value when there is one that is not empty, and the
// Host header when there is not.
function readCarelessOrigin(request) {
const forwardedHost = String(request.headers['x-forwarded-host'] || '').split(',')[0].trim()
const name = forwardedHost || String(request.headers.host || '')
return 'https://' + name
}
// CAREFUL: every link starts with the one configured origin, whatever the
// request says.
function chooseOrigin(version, request) {
if (version === 'careful') return CANONICAL_ORIGIN
return readCarelessOrigin(request)
}
// The tour page carries two absolute links: a canonical tag and a booking
// link. The page is marked public, and the lab cache stores a 200 reply to a
// GET request when it is marked that way.
function sendTourPage(response, origin) {
const page = [
'<link rel="canonical" href="' + origin + TOUR_PATH + '">',
'<h1>Sunrise paddle</h1>',
'<a href="' + origin + TOUR_PATH + '/book">Book this tour</a>',
].join(NEWLINE)
response.writeHead(200, {
'content-type': 'text/html',
'content-length': Buffer.byteLength(page),
'cache-control': 'public, max-age=60',
})
response.end(page)
}
// Writes a reset message to the outbox when the address has an account. The
// reply is the same either way. The token is a counter, so every run prints
// the same text. It is not how a real reset token is made.
async function answerResetRequest(state, request, response, origin) {
const email = new URLSearchParams(await readStream(request)).get('email')
if (email === LAB_ACCOUNT_EMAIL) {
state.tokenCount += 1
const token = 'lab-token-' + String(state.tokenCount).padStart(4, '0')
state.outbox.push({ to: email, link: origin + '/reset?token=' + token })
}
sendPlainText(response, 200, RESET_REPLY)
}
async function answerRequest(version, state, request, response) {
state.received.push({ host: request.headers.host, forwardedHost: request.headers['x-forwarded-host'] })
// CAREFUL: a Host header that is not on the allow-list is refused before
// any route runs.
if (version === 'careful' && !isServedHost(request.headers.host)) {
return sendPlainText(response, REFUSAL_STATUS, REFUSAL_TEXT)
}
const origin = chooseOrigin(version, request)
if (request.method === 'GET' && request.url === TOUR_PATH) return sendTourPage(response, origin)
if (request.method === 'POST' && request.url === RESET_PATH) return answerResetRequest(state, request, response, origin)
sendPlainText(response, 404, 'Not found')
}
// Returns the server with the two lists the lab reads afterwards: the outbox,
// and the Host and X-Forwarded-Host headers of every request that arrived.
export function createApp(version) {
const state = { outbox: [], received: [], tokenCount: 0 }
const server = http.createServer(function (request, response) {
answerRequest(version, state, request, response).catch(function (error) {
sendPlainText(response, 500, 'Lab error: ' + error.message)
})
})
return { server: server, outbox: state.outbox, received: state.received }
}
================================================================
FILE 4 OF 10: proxy.mjs
================================================================
// proxy.mjs: a small reverse proxy written for this lab, in two versions.
// Illustration only. It does not show how any real proxy, load balancer or
// CDN behaves. Both versions send the Host header on as they received it.
import http from 'node:http'
import { forwardRequest, readStream, sendPlainText, sendReply } from './forward.mjs'
import { REFUSAL_STATUS, REFUSAL_TEXT, isServedHost, readHostName } from './lab-settings.mjs'
// CARELESS: passes on every header it received, a client's X-Forwarded-Host
// included. It writes X-Forwarded-Host itself only when the client sent none
// or sent an empty one.
function buildCarelessHeaders(request) {
const headers = Object.assign({}, request.headers)
if (!headers['x-forwarded-host']) headers['x-forwarded-host'] = request.headers.host
return headers
}
// CAREFUL: writes X-Forwarded-Host from the Host header it has just checked,
// which replaces whatever the client sent under that name.
function buildCarefulHeaders(request) {
const headers = Object.assign({}, request.headers)
headers['x-forwarded-host'] = readHostName(request.headers.host)
return headers
}
async function answerRequest(version, appPort, request, response) {
// CAREFUL: a Host header that is not on the allow-list is refused here, and
// nothing is sent on to the application.
if (version === 'careful' && !isServedHost(request.headers.host)) {
return sendPlainText(response, REFUSAL_STATUS, REFUSAL_TEXT)
}
const headers = version === 'careful' ? buildCarefulHeaders(request) : buildCarelessHeaders(request)
const body = await readStream(request)
sendReply(response, await forwardRequest(appPort, request, headers, body), {})
}
export function createProxy(version, appPort) {
return http.createServer(function (request, response) {
answerRequest(version, appPort, request, response).catch(function () {
sendPlainText(response, 502, 'The lab application did not answer.')
})
})
}
================================================================
FILE 5 OF 10: cache.mjs
================================================================
// cache.mjs: a small shared cache written for this lab, in two versions.
// Illustration only. It does not show how any real cache or CDN behaves.
// The cache holds its entries in memory and never expires or removes one:
// it does not read max-age. Each createCache call starts with no entries,
// and the lab starts a fresh cache for each case. When it has no stored
// entry for a request, either version sends every request header on to the
// application.
import http from 'node:http'
import { forwardRequest, readStream, sendPlainText, sendReply } from './forward.mjs'
import { readHostName } from './lab-settings.mjs'
// CARELESS: the key is the method and request.url. Every lab request names a
// path with no query string, so two lab requests with one method and one path
// have the same key whatever their Host headers say.
// CAREFUL: the key also holds the Host header, lower-cased and without a port.
function buildCacheKey(version, request) {
if (version === 'careful') return request.method + ' ' + readHostName(request.headers.host) + ' ' + request.url
return request.method + ' ' + request.url
}
// A reply is stored only when it is a 200 answer to a GET request and the
// application marked it public.
function isStorable(request, reply) {
const cacheControl = String(reply.headers['cache-control'] || '')
return request.method === 'GET' && reply.status === 200 && cacheControl.includes('public')
}
async function answerRequest(version, appPort, entries, request, response) {
const key = buildCacheKey(version, request)
const stored = entries.get(key)
if (stored) return sendReply(response, stored, { 'x-lab-cache': 'HIT' })
const body = await readStream(request)
const reply = await forwardRequest(appPort, request, Object.assign({}, request.headers), body)
if (isStorable(request, reply)) entries.set(key, reply)
sendReply(response, reply, { 'x-lab-cache': 'MISS' })
}
// Returns the server with the map of stored entries, which the lab reads
// afterwards.
export function createCache(version, appPort) {
const entries = new Map()
const server = http.createServer(function (request, response) {
answerRequest(version, appPort, entries, request, response).catch(function () {
sendPlainText(response, 502, 'The lab application did not answer.')
})
})
return { server: server, entries: entries }
}
================================================================
FILE 6 OF 10: lab-stack.mjs
================================================================
// lab-stack.mjs: starts the application, the proxy and the cache for one
// version, each on 127.0.0.1 at a port the system picks, and stops them again.
// The proxy and the cache each send their requests straight to the
// application.
import { createApp } from './app.mjs'
import { createCache } from './cache.mjs'
import { VERSIONS } from './lab-settings.mjs'
import { createProxy } from './proxy.mjs'
function listen(server) {
return new Promise(function (resolve) {
server.listen(0, '127.0.0.1', function () { resolve(server.address().port) })
})
}
function stop(server) {
server.closeAllConnections()
return new Promise(function (resolve) { server.close(resolve) })
}
// Resolves with the port of each server, the application's two lists, the
// cache's map of entries and a function that stops all three servers.
export async function startStack(version) {
if (!VERSIONS.includes(version)) throw new Error('Unknown version: ' + version)
const app = createApp(version)
const appPort = await listen(app.server)
const proxyServer = createProxy(version, appPort)
const cache = createCache(version, appPort)
const ports = { application: appPort, 'reverse proxy': await listen(proxyServer), cache: await listen(cache.server) }
return {
ports: ports,
outbox: app.outbox,
received: app.received,
cacheEntries: cache.entries,
close: function () { return Promise.all([stop(cache.server), stop(proxyServer), stop(app.server)]) },
}
}
================================================================
FILE 7 OF 10: lab-client.mjs
================================================================
// lab-client.mjs: builds the text of one HTTP/1.1 request, writes it to a lab
// server on 127.0.0.1 and reads the reply. The client never connects to a
// host name. It sends the names in the lab as header values inside these
// requests, and every connection it opens goes to the literal address
// 127.0.0.1.
import net from 'node:net'
import { CRLF, LAB_ACCOUNT_EMAIL, RESET_PATH, TOUR_PATH } from './lab-settings.mjs'
// The text of a request: the request line, each header, a blank line, then
// the body.
function buildRequestText(method, path, headers, body) {
const lines = [method + ' ' + path + ' HTTP/1.1']
for (const header of headers) lines.push(header[0] + ': ' + header[1])
return lines.join(CRLF) + CRLF + CRLF + body
}
// A GET request for the tour page with the host headers the case names.
export function buildPageRequest(hostHeaders) {
const headers = hostHeaders.concat([['Connection', 'close']])
return buildRequestText('GET', TOUR_PATH, headers, '')
}
// A POST request that asks for a reset link for the lab's one account, with
// the host headers the case names.
export function buildResetRequest(hostHeaders) {
const body = 'email=' + encodeURIComponent(LAB_ACCOUNT_EMAIL)
const headers = hostHeaders.concat([
['Content-Type', 'application/x-www-form-urlencoded'],
['Content-Length', String(Buffer.byteLength(body))],
['Connection', 'close'],
])
return buildRequestText('POST', RESET_PATH, headers, body)
}
// Splits a reply into its status code, its headers (names lower-cased) and
// its body.
function parseReply(text) {
const headEnd = text.indexOf(CRLF + CRLF)
const headLines = text.slice(0, headEnd).split(CRLF)
const headers = {}
for (const line of headLines.slice(1)) {
const colon = line.indexOf(':')
headers[line.slice(0, colon).toLowerCase()] = line.slice(colon + 1).trim()
}
return { status: Number(headLines[0].split(' ')[1]), headers: headers, body: text.slice(headEnd + 4) }
}
// Writes the request text to 127.0.0.1 at the given port and resolves with
// the parsed reply once the server closes the connection.
export function sendRequest(port, requestText) {
return new Promise(function (resolve, reject) {
let reply = ''
const socket = net.connect({ host: '127.0.0.1', port: port }, function () { socket.write(requestText) })
socket.setEncoding('utf8')
socket.on('data', function (chunk) { reply += chunk })
socket.on('end', function () { resolve(parseReply(reply)) })
socket.on('error', reject)
})
}
================================================================
FILE 8 OF 10: cases.mjs
================================================================
// cases.mjs: the seven cases of the test pack. Each case lists the requests
// to send. runCase starts a fresh lab stack, sends them and returns what was
// observed. run-cases.mjs prints the observations and trusted-host.test.mjs
// asserts on them.
import { buildPageRequest, buildResetRequest, sendRequest } from './lab-client.mjs'
import { CANONICAL_HOST, OTHER_HOST, SECOND_SERVED_HOST, listOrigins } from './lab-settings.mjs'
import { startStack } from './lab-stack.mjs'
// target is the lab server the request is written to. kind is "page" for a
// GET of the tour page and "reset" for a POST that asks for a reset link.
export const CASES = [
{
id: '1A',
title: 'Absolute URL generation. The Host header names a host the application does not serve.',
steps: [{ target: 'application', kind: 'page', hostHeaders: [['Host', OTHER_HOST]] }],
},
{
id: '1B',
title: 'Absolute URL generation. The Host header is the second name the application serves.',
steps: [{ target: 'application', kind: 'page', hostHeaders: [['Host', SECOND_SERVED_HOST]] }],
},
{
id: '2A',
title: 'Password reset link. The Host header names a host the application does not serve.',
steps: [{ target: 'application', kind: 'reset', hostHeaders: [['Host', OTHER_HOST]] }],
},
{
id: '2B',
title: 'Password reset link. The Host header is the second name the application serves.',
steps: [{ target: 'application', kind: 'reset', hostHeaders: [['Host', SECOND_SERVED_HOST]] }],
},
{
id: '3',
title: 'Cache variation. Three requests for one page through the cache, each with a different Host header.',
steps: [
{ target: 'cache', kind: 'page', hostHeaders: [['Host', OTHER_HOST]] },
{ target: 'cache', kind: 'page', hostHeaders: [['Host', CANONICAL_HOST]] },
{ target: 'cache', kind: 'page', hostHeaders: [['Host', SECOND_SERVED_HOST]] },
],
},
{
id: '4A',
title: 'Proxy forwarding. A reset request through the proxy whose Host header names a host nobody serves.',
steps: [{ target: 'reverse proxy', kind: 'reset', hostHeaders: [['Host', OTHER_HOST]] }],
},
{
id: '4B',
title: 'Proxy forwarding. A reset request through the proxy with the served Host header and a client-written X-Forwarded-Host.',
steps: [{ target: 'reverse proxy', kind: 'reset', hostHeaders: [['Host', CANONICAL_HOST], ['X-Forwarded-Host', OTHER_HOST]] }],
},
]
// Sends one request and records its text, the status and body of the reply,
// the lab cache header when there is one, and the origins found in the body.
async function runStep(stack, step) {
const requestText = step.kind === 'reset' ? buildResetRequest(step.hostHeaders) : buildPageRequest(step.hostHeaders)
const reply = await sendRequest(stack.ports[step.target], requestText)
return {
target: step.target,
kind: step.kind,
requestText: requestText,
status: reply.status,
body: reply.body,
cacheStatus: reply.headers['x-lab-cache'],
origins: listOrigins(reply.body),
}
}
// The key of each stored cache entry with the origins found in its body.
function listCacheEntries(stack) {
const entries = []
for (const pair of stack.cacheEntries) entries.push({ key: pair[0], origins: listOrigins(pair[1].body) })
return entries
}
// Runs one case against a fresh stack of the given version, then stops the
// stack. Resolves with the steps, the outbox, the host headers the
// application received and the entries the cache holds.
export async function runCase(testCase, version) {
const stack = await startStack(version)
try {
const steps = []
for (const step of testCase.steps) steps.push(await runStep(stack, step))
return { steps: steps, outbox: stack.outbox.slice(), received: stack.received.slice(), cacheEntries: listCacheEntries(stack) }
} finally {
await stack.close()
}
}
// Every origin a case produced: in reply bodies, in outbox links and in
// stored cache entries.
export function listObservedOrigins(observation) {
const origins = []
for (const step of observation.steps) origins.push(...step.origins)
for (const message of observation.outbox) origins.push(...listOrigins(message.link))
for (const entry of observation.cacheEntries) origins.push(...entry.origins)
return Array.from(new Set(origins))
}
================================================================
FILE 9 OF 10: run-cases.mjs
================================================================
// run-cases.mjs: runs the seven cases against one version of the lab and
// prints, for each, the request as sent, the status of the reply, the body of
// a refusal and where each generated origin ended up.
// Usage: node run-cases.mjs careless or node run-cases.mjs careful
import { CASES, listObservedOrigins, runCase } from './cases.mjs'
import { CANONICAL_ORIGIN, CRLF, REFUSAL_STATUS, SERVED_HOSTS, listOrigins } from './lab-settings.mjs'
function describeOrigins(origins) {
return origins.length === 0 ? 'none' : origins.join(', ')
}
// Prints the request line and headers as sent, then marks the blank line and
// prints the body when the request has one.
function printRequestText(requestText) {
const parts = requestText.split(CRLF + CRLF)
for (const line of parts[0].split(CRLF)) console.log(' ' + line)
if (parts[1] === '') return
console.log(' (blank line)')
console.log(' ' + parts[1])
}
function printStep(number, step) {
console.log(' Request ' + number + ', written to the ' + step.target + ' on 127.0.0.1:')
printRequestText(step.requestText)
console.log(' Status: ' + step.status)
if (step.status === REFUSAL_STATUS) console.log(' Body: ' + step.body)
if (step.cacheStatus) console.log(' Cache: ' + step.cacheStatus)
if (step.kind === 'page') console.log(' Origin in the links of the page: ' + describeOrigins(step.origins))
}
function printOutbox(outbox) {
console.log(' Outbox: ' + outbox.length + (outbox.length === 1 ? ' message' : ' messages'))
for (const message of outbox) {
console.log(' To: ' + message.to)
console.log(' Link: ' + message.link)
console.log(' Origin in the outbox link: ' + describeOrigins(listOrigins(message.link)))
}
}
function printReceived(received) {
if (received.length === 0) console.log(' The application received: nothing. The proxy answered.')
for (const headers of received) {
console.log(' The application received: Host: ' + headers.host + ' and X-Forwarded-Host: ' + headers.forwardedHost)
}
}
function printCacheEntries(entries) {
console.log(' Entries the cache holds afterwards: ' + entries.length)
for (const entry of entries) {
console.log(' Key: ' + entry.key)
console.log(' Origin in the stored page: ' + describeOrigins(entry.origins))
}
}
// One line that sums the case up, chosen from the origins alone. When the
// case produced no origin the line says "refused, and no link was generated":
// this function does not check the status, which printStep prints above it.
// Otherwise the line says that every generated link carries the configured
// origin, or names the origins that are not the configured one.
function describeResult(observation) {
const origins = listObservedOrigins(observation)
const others = origins.filter(function (origin) { return origin !== CANONICAL_ORIGIN })
if (origins.length === 0) return 'refused, and no link was generated'
if (others.length === 0) return 'every generated link carries the configured origin'
return 'NOT the configured origin: ' + others.join(', ')
}
function printCase(testCase, observation) {
console.log('')
console.log('CASE ' + testCase.id + ' ' + testCase.title)
observation.steps.forEach(function (step, index) { printStep(index + 1, step) })
const firstStep = testCase.steps[0]
if (firstStep.kind === 'reset') printOutbox(observation.outbox)
if (firstStep.target === 'reverse proxy') printReceived(observation.received)
if (firstStep.target === 'cache') printCacheEntries(observation.cacheEntries)
console.log(' Result: ' + describeResult(observation))
}
async function main() {
const version = process.argv[2]
console.log('TRUSTED-HOST LAB, VERSION: ' + version)
console.log('Configured origin: ' + CANONICAL_ORIGIN)
console.log('Served host names: ' + SERVED_HOSTS.join(', '))
for (const testCase of CASES) printCase(testCase, await runCase(testCase, version))
}
main().catch(function (error) {
console.error(error.message)
process.exitCode = 1
})
================================================================
FILE 10 OF 10: trusted-host.test.mjs
================================================================
// trusted-host.test.mjs: the regression tests, one for each case. Set
// LAB_VERSION to careless or careful. Without it the tests run against the
// careful version. Each test asserts what the careful version does.
import assert from 'node:assert/strict'
import test from 'node:test'
import { CASES, runCase } from './cases.mjs'
import { CANONICAL_HOST, CANONICAL_ORIGIN, REFUSAL_STATUS, listOrigins } from './lab-settings.mjs'
const VERSION = process.env.LAB_VERSION || 'careful'
function observe(caseId) {
const testCase = CASES.find(function (candidate) { return candidate.id === caseId })
return runCase(testCase, VERSION)
}
function listOutboxOrigins(observation) {
const origins = []
for (const message of observation.outbox) origins.push(...listOrigins(message.link))
return origins
}
test('1A a page requested with an unknown Host header is refused', async function () {
const observation = await observe('1A')
assert.equal(observation.steps[0].status, REFUSAL_STATUS)
assert.deepEqual(observation.steps[0].origins, [])
})
test('1B a page requested through the second served name links only to the configured origin', async function () {
const observation = await observe('1B')
assert.equal(observation.steps[0].status, 200)
assert.deepEqual(observation.steps[0].origins, [CANONICAL_ORIGIN])
})
test('2A a reset request with an unknown Host header is refused and writes no message', async function () {
const observation = await observe('2A')
assert.equal(observation.steps[0].status, REFUSAL_STATUS)
assert.equal(observation.outbox.length, 0)
})
test('2B a reset request through the second served name writes a link to the configured origin', async function () {
const observation = await observe('2B')
assert.equal(observation.steps[0].status, 200)
assert.deepEqual(listOutboxOrigins(observation), [CANONICAL_ORIGIN])
})
test('3 a visitor is not served a page that was built for another Host header', async function () {
const observation = await observe('3')
assert.deepEqual(observation.steps[1].origins, [CANONICAL_ORIGIN])
assert.deepEqual(observation.steps[2].origins, [CANONICAL_ORIGIN])
for (const entry of observation.cacheEntries) assert.deepEqual(entry.origins, [CANONICAL_ORIGIN])
})
test('4A the proxy refuses an unknown Host header and the application receives nothing', async function () {
const observation = await observe('4A')
assert.equal(observation.steps[0].status, REFUSAL_STATUS)
assert.equal(observation.received.length, 0)
assert.equal(observation.outbox.length, 0)
})
test('4B a client-written X-Forwarded-Host reaches neither the application nor the reset link', async function () {
const observation = await observe('4B')
assert.equal(observation.steps[0].status, 200)
assert.equal(observation.received[0].forwardedHost, CANONICAL_HOST)
assert.deepEqual(listOutboxOrigins(observation), [CANONICAL_ORIGIN])
})
================================================================
PART 3: THE RECORDED RUN
================================================================
Each command was run from the trusted-host-lab folder, in this order. Every output is copied from that run by a script. One output has cuts: in step 2, the first line of each of the seven stack traces held a file path on the computer that ran the lab, so those seven lines were cut, and each cut is marked where it was made.
Step 1. Command: node run-cases.mjs careless
TRUSTED-HOST LAB, VERSION: careless
Configured origin: https://bookings.tideline.example
Served host names: bookings.tideline.example, tideline-tours.example
CASE 1A Absolute URL generation. The Host header names a host the application does not serve.
Request 1, written to the application on 127.0.0.1:
GET /tours/sunrise-paddle HTTP/1.1
Host: other-host.test
Connection: close
Status: 200
Origin in the links of the page: https://other-host.test
Result: NOT the configured origin: https://other-host.test
CASE 1B Absolute URL generation. The Host header is the second name the application serves.
Request 1, written to the application on 127.0.0.1:
GET /tours/sunrise-paddle HTTP/1.1
Host: tideline-tours.example
Connection: close
Status: 200
Origin in the links of the page: https://tideline-tours.example
Result: NOT the configured origin: https://tideline-tours.example
CASE 2A Password reset link. The Host header names a host the application does not serve.
Request 1, written to the application on 127.0.0.1:
POST /password-reset HTTP/1.1
Host: other-host.test
Content-Type: application/x-www-form-urlencoded
Content-Length: 29
Connection: close
(blank line)
email=alex%40customer.example
Status: 200
Outbox: 1 message
To: alex@customer.example
Link: https://other-host.test/reset?token=lab-token-0001
Origin in the outbox link: https://other-host.test
Result: NOT the configured origin: https://other-host.test
CASE 2B Password reset link. The Host header is the second name the application serves.
Request 1, written to the application on 127.0.0.1:
POST /password-reset HTTP/1.1
Host: tideline-tours.example
Content-Type: application/x-www-form-urlencoded
Content-Length: 29
Connection: close
(blank line)
email=alex%40customer.example
Status: 200
Outbox: 1 message
To: alex@customer.example
Link: https://tideline-tours.example/reset?token=lab-token-0001
Origin in the outbox link: https://tideline-tours.example
Result: NOT the configured origin: https://tideline-tours.example
CASE 3 Cache variation. Three requests for one page through the cache, each with a different Host header.
Request 1, written to the cache on 127.0.0.1:
GET /tours/sunrise-paddle HTTP/1.1
Host: other-host.test
Connection: close
Status: 200
Cache: MISS
Origin in the links of the page: https://other-host.test
Request 2, written to the cache on 127.0.0.1:
GET /tours/sunrise-paddle HTTP/1.1
Host: bookings.tideline.example
Connection: close
Status: 200
Cache: HIT
Origin in the links of the page: https://other-host.test
Request 3, written to the cache on 127.0.0.1:
GET /tours/sunrise-paddle HTTP/1.1
Host: tideline-tours.example
Connection: close
Status: 200
Cache: HIT
Origin in the links of the page: https://other-host.test
Entries the cache holds afterwards: 1
Key: GET /tours/sunrise-paddle
Origin in the stored page: https://other-host.test
Result: NOT the configured origin: https://other-host.test
CASE 4A Proxy forwarding. A reset request through the proxy whose Host header names a host nobody serves.
Request 1, written to the reverse proxy on 127.0.0.1:
POST /password-reset HTTP/1.1
Host: other-host.test
Content-Type: application/x-www-form-urlencoded
Content-Length: 29
Connection: close
(blank line)
email=alex%40customer.example
Status: 200
Outbox: 1 message
To: alex@customer.example
Link: https://other-host.test/reset?token=lab-token-0001
Origin in the outbox link: https://other-host.test
The application received: Host: other-host.test and X-Forwarded-Host: other-host.test
Result: NOT the configured origin: https://other-host.test
CASE 4B Proxy forwarding. A reset request through the proxy with the served Host header and a client-written X-Forwarded-Host.
Request 1, written to the reverse proxy on 127.0.0.1:
POST /password-reset HTTP/1.1
Host: bookings.tideline.example
X-Forwarded-Host: other-host.test
Content-Type: application/x-www-form-urlencoded
Content-Length: 29
Connection: close
(blank line)
email=alex%40customer.example
Status: 200
Outbox: 1 message
To: alex@customer.example
Link: https://other-host.test/reset?token=lab-token-0001
Origin in the outbox link: https://other-host.test
The application received: Host: bookings.tideline.example and X-Forwarded-Host: other-host.test
Result: NOT the configured origin: https://other-host.test
Exit code: 0
Reading it: every case ends with an origin that is not the configured one. In 1A, 2A and 4A it is the name the request sent in its Host header. In 1B and 2B it is the application's own second name, which is the same mistake with no hostile request involved. In case 3 the page built for other-host.test was stored under the key GET /tours/sunrise-paddle, and the two requests that followed, each with a served name in its Host header, were answered with that page as a cache HIT. In 4B the Host header was the served name throughout, and the origin in the reset link came from the X-Forwarded-Host header the client wrote.
Step 2. Command: LAB_VERSION=careless node --test trusted-host.test.mjs
✖ 1A a page requested with an unknown Host header is refused (14.02975ms)
✖ 1B a page requested through the second served name links only to the configured origin (2.79675ms)
✖ 2A a reset request with an unknown Host header is refused and writes no message (1.385ms)
✖ 2B a reset request through the second served name writes a link to the configured origin (1.033708ms)
✖ 3 a visitor is not served a page that was built for another Host header (3.648458ms)
✖ 4A the proxy refuses an unknown Host header and the application receives nothing (1.767834ms)
✖ 4B a client-written X-Forwarded-Host reaches neither the application nor the reset link (1.293416ms)
ℹ tests 7
ℹ suites 0
ℹ pass 0
ℹ fail 7
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 132.228416
✖ failing tests:
test at trusted-host.test.mjs:23:1
✖ 1A a page requested with an unknown Host header is refused (14.02975ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
200 !== 421
(cut: 1 line that held a file path on the computer that ran the lab)
at process.processTicksAndRejections (node:internal/process/task_queues:104:5)
at async Test.run (node:internal/test_runner/test:1208:7)
at async startSubtestAfterBootstrap (node:internal/test_runner/harness:385:3) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 200,
expected: 421,
operator: 'strictEqual',
diff: 'simple'
}
test at trusted-host.test.mjs:29:1
✖ 1B a page requested through the second served name links only to the configured origin (2.79675ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
[
+ 'https://tideline-tours.example'
- 'https://bookings.tideline.example'
]
(cut: 1 line that held a file path on the computer that ran the lab)
at process.processTicksAndRejections (node:internal/process/task_queues:104:5)
at async Test.run (node:internal/test_runner/test:1208:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:831:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: [ 'https://tideline-tours.example' ],
expected: [ 'https://bookings.tideline.example' ],
operator: 'deepStrictEqual',
diff: 'simple'
}
test at trusted-host.test.mjs:35:1
✖ 2A a reset request with an unknown Host header is refused and writes no message (1.385ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
200 !== 421
(cut: 1 line that held a file path on the computer that ran the lab)
at process.processTicksAndRejections (node:internal/process/task_queues:104:5)
at async Test.run (node:internal/test_runner/test:1208:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:831:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 200,
expected: 421,
operator: 'strictEqual',
diff: 'simple'
}
test at trusted-host.test.mjs:41:1
✖ 2B a reset request through the second served name writes a link to the configured origin (1.033708ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
[
+ 'https://tideline-tours.example'
- 'https://bookings.tideline.example'
]
(cut: 1 line that held a file path on the computer that ran the lab)
at process.processTicksAndRejections (node:internal/process/task_queues:104:5)
at async Test.run (node:internal/test_runner/test:1208:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:831:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: [ 'https://tideline-tours.example' ],
expected: [ 'https://bookings.tideline.example' ],
operator: 'deepStrictEqual',
diff: 'simple'
}
test at trusted-host.test.mjs:47:1
✖ 3 a visitor is not served a page that was built for another Host header (3.648458ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
[
+ 'https://other-host.test'
- 'https://bookings.tideline.example'
]
(cut: 1 line that held a file path on the computer that ran the lab)
at process.processTicksAndRejections (node:internal/process/task_queues:104:5)
at async Test.run (node:internal/test_runner/test:1208:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:831:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: [ 'https://other-host.test' ],
expected: [ 'https://bookings.tideline.example' ],
operator: 'deepStrictEqual',
diff: 'simple'
}
test at trusted-host.test.mjs:54:1
✖ 4A the proxy refuses an unknown Host header and the application receives nothing (1.767834ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
200 !== 421
(cut: 1 line that held a file path on the computer that ran the lab)
at process.processTicksAndRejections (node:internal/process/task_queues:104:5)
at async Test.run (node:internal/test_runner/test:1208:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:831:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 200,
expected: 421,
operator: 'strictEqual',
diff: 'simple'
}
test at trusted-host.test.mjs:61:1
✖ 4B a client-written X-Forwarded-Host reaches neither the application nor the reset link (1.293416ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ 'other-host.test'
- 'bookings.tideline.example'
(cut: 1 line that held a file path on the computer that ran the lab)
at process.processTicksAndRejections (node:internal/process/task_queues:104:5)
at async Test.run (node:internal/test_runner/test:1208:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:831:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 'other-host.test',
expected: 'bookings.tideline.example',
operator: 'strictEqual',
diff: 'simple'
}
Exit code: 1
Reading it: all seven tests fail and the process exits with code 1. The reporter prints the seven results and the totals, then each failure again with its assertion. Under each failure, the first stack frame held a file path and was cut.
Step 3. Command: node run-cases.mjs careful
TRUSTED-HOST LAB, VERSION: careful
Configured origin: https://bookings.tideline.example
Served host names: bookings.tideline.example, tideline-tours.example
CASE 1A Absolute URL generation. The Host header names a host the application does not serve.
Request 1, written to the application on 127.0.0.1:
GET /tours/sunrise-paddle HTTP/1.1
Host: other-host.test
Connection: close
Status: 421
Body: Misdirected Request: this server does not serve that host name.
Origin in the links of the page: none
Result: refused, and no link was generated
CASE 1B Absolute URL generation. The Host header is the second name the application serves.
Request 1, written to the application on 127.0.0.1:
GET /tours/sunrise-paddle HTTP/1.1
Host: tideline-tours.example
Connection: close
Status: 200
Origin in the links of the page: https://bookings.tideline.example
Result: every generated link carries the configured origin
CASE 2A Password reset link. The Host header names a host the application does not serve.
Request 1, written to the application on 127.0.0.1:
POST /password-reset HTTP/1.1
Host: other-host.test
Content-Type: application/x-www-form-urlencoded
Content-Length: 29
Connection: close
(blank line)
email=alex%40customer.example
Status: 421
Body: Misdirected Request: this server does not serve that host name.
Outbox: 0 messages
Result: refused, and no link was generated
CASE 2B Password reset link. The Host header is the second name the application serves.
Request 1, written to the application on 127.0.0.1:
POST /password-reset HTTP/1.1
Host: tideline-tours.example
Content-Type: application/x-www-form-urlencoded
Content-Length: 29
Connection: close
(blank line)
email=alex%40customer.example
Status: 200
Outbox: 1 message
To: alex@customer.example
Link: https://bookings.tideline.example/reset?token=lab-token-0001
Origin in the outbox link: https://bookings.tideline.example
Result: every generated link carries the configured origin
CASE 3 Cache variation. Three requests for one page through the cache, each with a different Host header.
Request 1, written to the cache on 127.0.0.1:
GET /tours/sunrise-paddle HTTP/1.1
Host: other-host.test
Connection: close
Status: 421
Body: Misdirected Request: this server does not serve that host name.
Cache: MISS
Origin in the links of the page: none
Request 2, written to the cache on 127.0.0.1:
GET /tours/sunrise-paddle HTTP/1.1
Host: bookings.tideline.example
Connection: close
Status: 200
Cache: MISS
Origin in the links of the page: https://bookings.tideline.example
Request 3, written to the cache on 127.0.0.1:
GET /tours/sunrise-paddle HTTP/1.1
Host: tideline-tours.example
Connection: close
Status: 200
Cache: MISS
Origin in the links of the page: https://bookings.tideline.example
Entries the cache holds afterwards: 2
Key: GET bookings.tideline.example /tours/sunrise-paddle
Origin in the stored page: https://bookings.tideline.example
Key: GET tideline-tours.example /tours/sunrise-paddle
Origin in the stored page: https://bookings.tideline.example
Result: every generated link carries the configured origin
CASE 4A Proxy forwarding. A reset request through the proxy whose Host header names a host nobody serves.
Request 1, written to the reverse proxy on 127.0.0.1:
POST /password-reset HTTP/1.1
Host: other-host.test
Content-Type: application/x-www-form-urlencoded
Content-Length: 29
Connection: close
(blank line)
email=alex%40customer.example
Status: 421
Body: Misdirected Request: this server does not serve that host name.
Outbox: 0 messages
The application received: nothing. The proxy answered.
Result: refused, and no link was generated
CASE 4B Proxy forwarding. A reset request through the proxy with the served Host header and a client-written X-Forwarded-Host.
Request 1, written to the reverse proxy on 127.0.0.1:
POST /password-reset HTTP/1.1
Host: bookings.tideline.example
X-Forwarded-Host: other-host.test
Content-Type: application/x-www-form-urlencoded
Content-Length: 29
Connection: close
(blank line)
email=alex%40customer.example
Status: 200
Outbox: 1 message
To: alex@customer.example
Link: https://bookings.tideline.example/reset?token=lab-token-0001
Origin in the outbox link: https://bookings.tideline.example
The application received: Host: bookings.tideline.example and X-Forwarded-Host: bookings.tideline.example
Result: every generated link carries the configured origin
Exit code: 0
Reading it: the four requests that named other-host.test in the Host header were refused with 421 and the same fixed sentence: by the application in 1A, 2A and the first request of case 3, and by the proxy in 4A, where the application received nothing. Every link that was generated carries https://bookings.tideline.example, including those requested through tideline-tours.example. In case 3 the refused reply was not stored, and the cache holds one entry for each served name. In 4B the application received the X-Forwarded-Host value the proxy wrote, not the one the client sent.
Step 4. Command: LAB_VERSION=careful node --test trusted-host.test.mjs
✔ 1A a page requested with an unknown Host header is refused (13.425167ms)
✔ 1B a page requested through the second served name links only to the configured origin (1.004542ms)
✔ 2A a reset request with an unknown Host header is refused and writes no message (0.853375ms)
✔ 2B a reset request through the second served name writes a link to the configured origin (1.641875ms)
✔ 3 a visitor is not served a page that was built for another Host header (4.512ms)
✔ 4A the proxy refuses an unknown Host header and the application receives nothing (0.805792ms)
✔ 4B a client-written X-Forwarded-Host reaches neither the application nor the reset link (1.2835ms)
ℹ tests 7
ℹ suites 0
ℹ pass 7
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 132.983833
Exit code: 0
Reading it: all seven tests pass and the process exits with code 0.
================================================================
PART 4: THE SAME TESTS ON YOUR OWN APPLICATION
================================================================
Run these steps only on systems you own or are authorised in writing to test.
Before you change anything
[ ] Fill in the four rows of Part 1 against your test environment and keep the results as the Before column.
[ ] Write down which layer you expect to refuse an unknown name, and which header your application reads its name from.
Fix in this order
[ ] Put the public origin in configuration and build every full address from it. Search the code for every read of the Host header, of X-Forwarded-Host and of your framework's host helpers.
[ ] Turn on your framework's host allow-list with the names you serve and no wildcard.
[ ] Give your web server or proxy a default site that refuses names it does not serve.
[ ] Have the proxy in front of the application write the forwarded host header on every request, and turn on the framework's forwarded-header support only if the proxy does.
Prove it
[ ] Restart or redeploy whatever read the old settings.
[ ] Repeat the four rows. A row passes when the origin in what was generated is the configured one, or the request was refused.
[ ] Keep the requests, the responses and the test messages, with the date, as evidence.
Keep it proved
[ ] Adapt trusted-host.test.mjs: keep the assertions, and replace the lab client with requests to your staging address and a read of your test mailbox.
[ ] Run it in the release pipeline, so a release stops when a row fails.
[ ] Run the rows again when the CDN, the proxy, the framework version or the list of served names changes.What host header injection is
A web application sometimes has to write out its own address in full: in the link inside a password reset email, in a canonical tag, in a redirect to the sign-in page.
That address is a fact about where the application is deployed, so it belongs in configuration. Host header injection is the weakness that appears when the application reads it from the request instead. Every request names the site it is meant for, in the Host header or in a forwarded copy of it, and the name is written by whoever sends the request.
An application that builds a link from that name has let a stranger decide what the link says.
OWASP's Web Security Testing Guide (WSTG) has a test for it. In version 4.2, the current stable release, it is 4.7.17 Testing for Host Header Injection, with the id WSTG-INPV-17. Its summary says a web server commonly hosts several web applications on the same IP address, referring to each application via the virtual host, and that web servers often dispatch an incoming request to the target virtual host based on the value supplied in the Host header.
Without proper validation of the header value, it says, the attacker can supply invalid input to cause the web server to do four things: dispatch requests to the first virtual host on the list, cause a redirect to an attacker-controlled domain, perform web cache poisoning, and manipulate password reset functionality.
The latest edition of the guide, which its site says represents the latest contributions and may frequently change, files the test under a different id: 4.7.17 Host Header Injection, WSTG-INJT-17, in a section named Injection. It keeps the same two test objectives and adds a fifth outcome to the list: allowing access to virtual hosts that were not intended to be externally accessible. This page uses version 4.2 and its id unless it says otherwise.
PortSwigger's Web Security Academy, which is one vendor's teaching material and not a standard, uses the wider name HTTP Host header attacks for attacks that exploit websites handling the value of the Host header in an unsafe way.
It says attacks that involve injecting a payload directly into the Host header are often known as Host header injection attacks, and that the vulnerabilities typically arise due to the flawed assumption that the header is not user controllable.
On this page a host header attack and host header injection are the same problem, named once for what the sender does and once for where the value lands.
This guide owns one mistake and the controls that stop it. The mistake: the application takes its own name from the request when it builds an absolute URL, chooses a tenant or virtual host, or writes a link into an email. The controls: one configured origin for every generated link, an allow-list of host names enforced in the framework and at the proxy, a default virtual host that refuses unknown names, and a proxy that overwrites forwarded host headers instead of passing a client's copy on.
What the Host header is for, and who sets it
One server address can answer for many sites, so each request has to say which one it wants.
RFC 9110, HTTP Semantics, published in June 2022, says in section 7.2 that the Host header field in a request provides the host and port information from the target URI, enabling the origin server to distinguish among resources while servicing requests for multiple host names.
The same section says a user agent MUST generate a Host header field in a request unless it sends that information as an ":authority" pseudo-header field, which in HTTP/2 and HTTP/3 supplants the Host header in some cases.
RFC 9112, the HTTP/1.1 standard, adds in section 3.2 that a client MUST send a Host header field in all HTTP/1.1 request messages and, when the target URI includes an authority component, MUST send a value identical to that component, leaving out any userinfo. In plain terms, a browser copies the name from the address it was asked to open.
Those rules bind well-behaved clients. They do not bind the person at the keyboard, who can write a request with any name in it. The standards acknowledge this in their own way. Section 7.2 of RFC 9110 warns that since the host and port information acts as an application-level routing mechanism, it is a frequent target for malware seeking to poison a shared cache or redirect a request to an unintended server.
Apache HTTP Server's documentation says as much in a warning about CGI scripts under its UseCanonicalName directive: the client is essentially free to give whatever value they want as a hostname.
Four passages in the two RFCs cover what a server does with the name it is given.
- A missing or repeated header. RFC 9112 section 3.2: a server MUST respond with a 400 (Bad Request) status code to any HTTP/1.1 request message that lacks a Host header field, and to any request message that contains more than one Host header field line or a Host header field with an invalid field value.
- Two places for the name. A request line can carry a full address, the absolute-form, as well as a Host header. RFC 9112 section 3.2.2 settles which one counts: when an origin server receives a request with an absolute-form of request-target, it MUST ignore the received Host header field, if any, and instead use the host information of the request-target. A proxy that receives one MUST likewise ignore the received Host header field and replace it with the host information of the request-target. The same section says a server MUST accept the absolute-form in requests even though most HTTP/1.1 clients will only send it to a proxy.
- A name the server does not serve. RFC 9110 section 7.4 says that once a server has determined a request's target URI, it decides whether to process the request itself, forward the request to another server, redirect the client to a different resource, respond with an error, or drop the connection. That decision, it says, can be influenced by anything about the request or connection context, but is specifically directed at whether the server has been configured to process requests for that target URI and whether the connection context is appropriate for that request. It notes that a Host header field that differs from the connection's host or port might be expected if the connection is from a trusted gateway; otherwise, it might indicate an attempt to bypass security filters, trick the server into delivering non-public content, or poison a cache.
- A status for the refusal. RFC 9110 section 15.5.20 defines 421 (Misdirected Request): the request was directed at a server that is unable or unwilling to produce an authoritative response for the target URI. An origin server, or a gateway acting on behalf of the origin server, sends 421 to reject a target URI that does not match an origin for which the server has been configured, or does not match the connection context over which the request was received.
Section 7.4 of RFC 9110 makes one kind of rejection a requirement: unless the connection is from a trusted gateway, an origin server MUST reject a request if any scheme-specific requirements for the target URI are not met. Its opening sentence, quoted above, carries no requirement word: it says the server decides whether to process the request, forward it, redirect the client, respond with an error or drop the connection.
RFC 9112 section 3.3 says reconstructing the client's target URI is only half of the process for identifying a target resource, and that the other half is determining whether that target URI identifies a resource for which the server is willing and able to send a response.
Whether your stack makes that second decision, and at which layer, is the subject of the rest of this page.
Why the application behind a proxy sees a different name
An application does not have to face the internet itself.
Where a CDN, a load balancer or a reverse proxy takes the visitor's connection and opens its own connection to the application, the application sees the request that intermediary wrote. RFC 9110 section 3.7 calls this kind of intermediary a gateway, also known as a reverse proxy: one that acts as an origin server for the outbound connection but translates received requests and forwards them inbound to another server or servers.
What the application then finds in the Host header depends on how the intermediary is set up.
Of the three sources below, two are web servers documenting their own proxy modules, and the third is a framework's documentation saying what proxies usually do.
- nginx: its proxy module documentation gives the default as proxy_set_header Host $proxy_host, and defines $proxy_host as the name and port of a proxied server as specified in the proxy_pass directive. By default, it says, the Host header field from the original request is not passed to the proxied server. It shows ways to pass a name from the request instead, among them $http_host, for an unchanged Host request header field, and $host, whose value equals the server name in the Host request header field or the primary server name if this field is not present.
- Apache HTTP Server 2.4: the ProxyPreserveHost directive defaults to Off. When enabled, the mod_proxy documentation says, the option passes the Host line from the incoming request to the proxied host, instead of the hostname specified in the ProxyPass line. It adds that the option should normally be turned Off.
- ASP.NET Core 10.0: Microsoft's documentation on proxy servers and load balancers says that usually proxies do not modify the Host header.
What that means for the application
On this page's reading of those three, the application may receive the public name, an internal name such as the one in a proxy_pass line, or whatever the client typed, depending on a setting in a different layer. Code that builds a link from the Host header can be right behind one proxy and wrong behind another without a line of it changing.
Forwarded host headers
When the proxy rewrites the Host header, the original name has to travel some other way. RFC 7239 defines the standard carrier: the Forwarded header field, an OPTIONAL field whose parameters disclose information that is altered or lost when a proxy is involved in the path of the request.
Section 5.3 defines its host parameter, which is used to forward the original value of the Host header field, and gives a use for it: by the origin server, for example, if a reverse proxy is rewriting the Host header field to some internal host name.
The X-Forwarded-Host header does the same job under another name, and this page takes its meaning from products that document it. Apache's mod_proxy documentation says that in reverse-proxy mode mod_proxy_http adds several request headers in order to pass information to the origin server, and lists three: X-Forwarded-For, X-Forwarded-Host, which it describes as the original host requested by the client in the Host HTTP request header, and X-Forwarded-Server.
Microsoft's ASP.NET Core documentation describes X-Forwarded-Host as the original value of the Host header field.
PortSwigger calls it the de facto standard for this behaviour and says other headers serve a similar purpose, including X-Host, X-Forwarded-Server, X-HTTP-Host-Override and Forwarded.
A forwarded header is only as trustworthy as the last machine that wrote it. RFC 7239 section 8.1 says the Forwarded header field cannot be relied upon to be correct, as it may be modified, whether mistakenly or for malicious reasons, by every node on the way to the server, including the client making the request.
Section 4 says a proxy MAY remove all Forwarded header fields from a request. Apache gives the practical warning for its own headers: be careful when using them on the origin server, since they will contain more than one comma-separated value if the original request already contained one of these headers.
Where applications use the host name
An application that reads its name from the request does so in a handful of places.
Each is harmless while every request carries the right name, and each fails in its own way when one does not.
- Links in email. A reset, invitation or verification message has to carry a full address, because the reader opens it from outside the site. The next section explains why this is the costly case.
- Redirects. A redirect to a full address built from the request sends the browser wherever the header said. Apache HTTP Server 2.4 documents its own version: with UseCanonicalName Off, which its core documentation gives as the default, Apache httpd forms self-referential URLs using the hostname and port supplied by the client if any are supplied, and its example is the redirect it sends when a directory is requested without the trailing slash. The WSTG test says that in the simplest case, supplying another domain in the Host header may cause a 302 redirect to the supplied domain. A redirect whose destination comes from a parameter such as next or return_to is a different mistake, covered in the open redirects guide.
- Canonical and social tags. A canonical link or an Open Graph address written from the request carries whatever name the request did, in a tag whose whole job is to state the page's own address. The first case study in PortSwigger's 2018 paper Practical Web Cache Poisoning was an application that used the X-Forwarded-Host header to generate an Open Graph URL inside a meta tag.
- Choosing a tenant or a virtual host. Software that serves several customers from one deployment can use the host name to decide whose branding and data to load, and a web server uses it to pick which site answers. The latest edition of the WSTG test describes the second kind going wrong: a server may have virtual hosts that are not intended to be externally accessible, and it may be possible to reach one from outside the network by making a request with its name in the Host header. For a tenant, treat the name as a request to see that tenant's site and not as evidence of who is asking.
- Cache keys. A cache decides that two requests want the same page by comparing a key. If the name shapes the response but is not in the key, a page built for one name is served under another. The web cache poisoning guide covers unkeyed inputs of every kind, and case 3 of the lab on this page shows this one.
Two vendors' lists
Django's security documentation names three consequences in one sentence: Django uses the Host header provided by the client to construct URLs in certain cases, and while these values are sanitised to prevent cross-site scripting attacks, a fake Host value can be used for cross-site request forgery, cache poisoning attacks, and poisoning links in emails.
Microsoft's ASP.NET Core documentation on proxy servers and load balancers says that proxy servers, load balancers and other network appliances often obscure information about the request before it reaches the app, naming the original scheme and the originating client IP address, and that this information might be important in request processing, for example in redirects, authentication, link generation, policy evaluation and client geolocation.
Password reset poisoning: why the reset link is the costly case
Of everything an application writes with its own name in it, the password reset link is the one that carries a secret.
PortSwigger defines password reset poisoning as a technique whereby an attacker manipulates a vulnerable website into generating a password reset link pointing to a domain under their control, and says this can be leveraged to steal the secret tokens required to reset arbitrary users' passwords and, ultimately, compromise their accounts. It says the technique was first documented in 2013 by its Director of Research, James Kettle.
The mechanism needs no access to the victim's mailbox. In PortSwigger's account, the attacker submits a reset request on the victim's behalf with the Host header changed to a domain they control. The victim receives a genuine password reset email directly from the website, containing a valid reset token associated with their account, in which the domain name in the URL points to the attacker's server.
If the victim clicks the link, or it is fetched in some other way, for example by an antivirus scanner, the token is delivered to that server.
The WSTG test describes the same outcome, and says it is common for password reset functionality to include the Host header value when creating password reset links that use a generated secret token.
Three features of the flow raise the cost, on this page's reading. A forgotten-password form is open to people who are not signed in, so the request needs no account and no session. The message is genuine: your own system sends it, to a customer who has no reason to doubt it.
And the flow rests on one assumption, which PortSwigger states: the security of an emailed reset link relies on the principle that only the intended user has access to their email inbox and, therefore, to their unique token. This technique removes that assumption without touching the inbox.
The fix the sources give
OWASP's Forgot Password Cheat Sheet says not to rely on the Host header while creating the reset URLs, and that the URL should either be hard-coded or validated against a list of trusted domains. PortSwigger gives the same advice in other words: when you have to use absolute URLs, require the current domain to be specified in a configuration file and refer to that value instead of the Host header, an approach it says would eliminate the threat of password reset poisoning, for example.
Cases 2A, 2B and 4B of the lab show both halves. The careless application wrote a reset link beginning with whichever name the request carried. The careful one wrote https://bookings.tideline.example into the link every time, and wrote no message at all for a name it does not serve. Token lifetime, single use and what the form says about unknown addresses belong to the authentication failures guide.
Allowed hosts configuration: how six frameworks decide their own name
Frameworks differ on two questions: whether they check the Host header against a list before your code runs, and whether they read a forwarded header in its place.
Each statement below comes from that product's own documentation as it read on 14 November 2026, for the version named, and says nothing about any other version or product.
ALLOWED_HOSTS is a list of the host and domain names the site can serve. The settings reference calls it a security measure to prevent HTTP Host header attacks, which it says are possible even under many seemingly-safe web server configurations, and gives its default as an empty list.
A fully qualified name is matched against the request's Host header exactly, case-insensitively and not including the port. A value beginning with a period is a subdomain wildcard, and a value of '*' matches anything, in which case, the reference says, you are responsible to provide your own validation of the Host header. When DEBUG is True and ALLOWED_HOSTS is empty, the host is validated against .localhost, 127.0.0.1 and [::1].
The check lives in one method. The request reference says HttpRequest.get_host() returns the originating host using the X-Forwarded-Host header, if USE_X_FORWARDED_HOST is enabled, and the Host header, in that order, and raises DisallowedHost if the host is not in ALLOWED_HOSTS. The settings reference names the exception as SuspiciousOperation, and the exceptions reference lists DisallowedHost among its subclasses.
A SuspiciousOperation that reaches the handler level, the exceptions reference says, is logged at the Error level and results in an HttpResponseBadRequest, the response class with a 400 status code.
Three limits are in the documentation itself. The validation only applies via get_host(), so code that accesses the Host header directly from request.META bypasses it. USE_X_FORWARDED_HOST defaults to False, and the reference says it should only be enabled if a proxy which sets this header is in use. And the deployment checklist says that when DEBUG is False, Django does not work at all without a suitable value for ALLOWED_HOSTS.
Rails checks the host in a middleware, ActionDispatch::HostAuthorization, which the configuration guide describes as preventing against DNS rebinding and other Host header attacks. The list it checks is config.hosts. The guide says the middleware is included in the development environment by default, with a list that holds all IPv4 addresses, all IPv6 addresses, the localhost reserved domain and any additional hosts named in the RAILS_DEVELOPMENT_HOSTS environment variable.
In other environments, it says, config.hosts is empty and no Host header checks will be done, so guarding production means adding the allowed hosts yourself.
When a request comes to an unauthorised host, a default Rack application runs and responds with 403 Forbidden, which config.host_authorization can change.
Rails also shows a configured host built into a framework. The Action Mailer guide says that in order to add URLs to a mailer you need to set the host value to the application's domain first, because, unlike controllers, the mailer instance does not have any context about the incoming request.
The default host is configured once, in config.action_mailer.default_url_options. On this page's reading, a mailer that takes its host from that setting cannot be handed a different name by a request, and a mailer whose caller passes the request's host in as the host option is back to the original mistake.
Laravel's request documentation states its default plainly: Laravel will respond to all requests it receives regardless of the content of the HTTP request's Host header, and the Host header's value will be used when generating absolute URLs to your application during a web request. It says that typically you should configure your web server, such as Nginx or Apache, to only send requests to your application that match a given hostname, and that if you cannot customise the web server directly you may enable the TrustHosts middleware.
Its trustHosts method takes the hostnames the application should respond to, each treated as a regular expression, and incoming requests with other Host headers will be rejected.
By default, requests coming from subdomains of the application's URL are also trusted, unless the subdomains argument turns that off.
Forwarded headers are a separate setting, the TrustProxies middleware, which takes the proxies to trust and the proxy headers to accept from them. X-Forwarded-Host is among the headers in its example. The documentation says that if you are using Amazon AWS or another cloud load balancer provider, you may not know the IP addresses of your actual balancers, and that in this case you may use * to trust all proxies.
Microsoft's host filtering page says that Kestrel, the ASP.NET Core web server, largely ignores the host name and that Host headers aren't validated. As a workaround it offers host-filtering middleware, which is disabled by default and enabled by defining an AllowedHosts key in appsettings.json: a semicolon-delimited list of host names without port numbers.
The values *, 0.0.0.0 and [::] are all treated as the wildcard, and if any of them appears in the list, all non-empty Host header values are allowed, even if other entries are present.
Forwarded headers are handled by separate middleware. The proxy and load balancer page says that outside IIS integration when hosting out-of-process it is not enabled by default. For the default settings, it says, the ForwardedHeaders value is ForwardedHeaders.None, the desired forwarders must be set to enable the middleware, and only loopback addresses are configured for known proxies and known networks.
It describes the ForwardedHeaders option as identifying which forwarders should be processed, and says the middleware sets HttpContext.Request.Host using the X-Forwarded-Host header value. Its own AllowedHosts option restricts hosts by the X-Forwarded-Host header.
The default is an empty list, an empty list allows all hosts, and the page says failure to restrict the allowed hosts might allow a cyberattacker to spoof links generated by the service.
A note on the host filtering page says which list fits where: AllowedHosts on the forwarded headers middleware when the Host header is not preserved while forwarding requests with a reverse proxy server or load balancer, and AllowedHosts on the host-filtering middleware when Kestrel is used as a public-facing edge server or when the Host header is directly forwarded.
The Express 5.x API reference says req.hostname contains the hostname derived from the Host HTTP header, and that when the trust proxy setting does not evaluate to false the property instead gets the value from the X-Forwarded-Host header field, a header that, in the reference's words, can be set by the client or by the proxy.
If there is more than one X-Forwarded-Host header in the request, the value of the first header is used, and that includes a single header with comma-separated values, in which the first value is used.
Express's guide to running behind proxies gives false as the default for trust proxy, under which the app is understood as directly facing the client. It attaches a warning to the value true: it is important to ensure that the last reverse proxy trusted is removing or overwriting all of the X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto headers, otherwise it may be possible for the client to provide any value.
Neither of those two pages describes a list of allowed host names.
On this page's reading, an Express application that builds a link from req.hostname is relying on its own code, or on the layer in front of it, to check the name.
Two statements in the Next.js documentation bear on this. For the addresses in metadata, the generateMetadata reference provides metadataBase, a base URL prefix for metadata fields that require a fully qualified URL, typically set in the root layout, and says that using a relative path in a URL-based metadata field without configuring a metadataBase will cause a build error.
For Server Actions, the data security guide says Next.js compares the Origin header to the Host header, or X-Forwarded-Host, and aborts the request on a mismatch.
The Next.js security guide on this site covers that framework's advisories and how its Server Actions are tested.
What nginx and Apache do with a name they do not recognise
The web server in front of the application makes its own decision about the name, before any framework sees the request.
By the documentation quoted below, each of these two servers, left alone, hands an unknown name to the site listed first in the configuration.
nginx
nginx's page How nginx processes a request describes three virtual servers listening on one port. nginx tests only the request's Host header field to decide which server the request should be routed to, and if its value does not match any server name, or the request does not contain the header at all, nginx routes the request to the default server for the port.
The default server is the first one, unless the default_server parameter of the listen directive names another.
On this page's reading, an unknown name on nginx is answered by whichever site comes first until someone decides otherwise.
The same page shows a server that just drops requests that have no Host header: its server name is an empty string, and it returns 444, which nginx describes as a special non-standard code that closes the connection. Django's deployment checklist uses the same response for unknown names.
It says the web server in front of Django should respond with a static error page or ignore requests for incorrect hosts instead of forwarding the request to Django, and gives an nginx default server that returns 444 on an unrecognised host as its example.
Apache HTTP Server 2.4
Apache reaches the same place by its own rule. Its name-based virtual host documentation says that if no matching ServerName or ServerAlias is found in the set of virtual hosts containing the most specific matching IP address and port combination, then the first listed virtual host that matches that will be used.
Django's security documentation carries a separate warning that uses Apache as its example: even if Apache is configured such that a Django site is served from a non-default virtual host with the ServerName set, it is still possible for an HTTP request to match this virtual host and supply a fake Host header. Django therefore requires ALLOWED_HOSTS to be set explicitly rather than relying on web server configuration.
Apache also decides which name its own redirects carry. With UseCanonicalName On, the core documentation says, Apache httpd will use the hostname and port specified in the ServerName directive to construct the canonical name for the server, and this name is used in all self-referential URLs. The default is Off.
Why checking the host at one layer is not enough
A request can pass through a CDN or cache, a reverse proxy and then the application, and each of the three has its own idea of the request's name.
A check in one of them covers the header that layer reads. It says nothing about the header the next layer reads.
The WSTG test names the gap. Under the heading X-Forwarded Host Header Bypass, it says that in the event that Host header injection is mitigated by checking for invalid input injected via the Host header, the value can be supplied to the X-Forwarded-Host header instead. PortSwigger makes a related point about ambiguous requests: the code that validates the host and the code that does something vulnerable with it often reside in different application components or even on separate servers.
It adds that when an X-Forwarded-Host header is present many frameworks will refer to it instead, that this may be observed even when there is no front end that uses the header, and that some websites support the behaviour unintentionally, usually because one or more of these headers is enabled by default in some third-party technology that they use.
Case 4B of the lab is that gap in miniature. The request's Host header was the application's real name from start to finish, so a check on the Host header at any layer would have passed it. The other name travelled in X-Forwarded-Host. The careless proxy passed the client's copy on, the careless application preferred it to the Host header, and the reset link in the outbox began with https://other-host.test.
The gap opens from the other side too. Django's warning is about a web server configuration that seems to validate the Host header and may not in fact do so. Laravel's documentation says that typically the web server should do the filtering, and offers its middleware for when you cannot configure the server.
Where two layers each leave the check to the other, nobody makes it. This page's advice is a rule for every layer that reads a host name: it either checks the name against the list itself, or reads it from a header that the layer directly in front writes on every request.
Two documented behaviours that meet badly
Put two of the pages quoted above side by side. Apache says its forwarded headers will contain more than one comma-separated value if the original request already contained one of them. Express says that for a single X-Forwarded-Host header with comma-separated values, the first value is used.
Neither page mentions the other product, and Apache's does not say which value comes first. On this page's reading, a proxy that adds to a forwarded header and an application that picks one entry from it can between them leave the application reading a value the client wrote.
The careful proxy in the lab replaces the header instead of adding to it for that reason. Test your own pair before relying on either reading.
Host header validation: four controls and what each one covers
The four controls sit at different layers, and the careful version of the lab runs three of them, with the proxy's refusal standing in for the default virtual host.
They are listed in the order to adopt them.
Hold the site's public origin as a setting and build every absolute URL from it: links in email, redirects to full addresses, canonical and social tags, and return addresses handed to payment or sign-in providers. RFC 9110 section 4.3.1 defines the origin of a URI as the triple of scheme, host and port.
Configure the scheme together with the name for that reason. This control removes the weakness instead of filtering its input. It is the first of the two options OWASP's cheat sheet gives for reset URLs (hard-coded, or validated against a list of trusted domains), and it is what PortSwigger describes for absolute URLs (the current domain specified in a configuration file and used instead of the Host header).
PortSwigger also suggests checking whether each URL really needs to be absolute, because you will often find that you can use a relative URL instead.
In the lab, cases 1B and 2B sent the application's second served name, which any allow-list holding that name would accept. The careless version wrote links beginning with https://tideline-tours.example. The careful version wrote https://bookings.tideline.example into the page and the outbox. An application that serves several names on purpose, such as one for each customer, keeps a list of origins in configuration and chooses from it by a rule of its own. The request can select an entry. It cannot supply one.
List the names the application serves and refuse every other. The frameworks above provide the list under different names: ALLOWED_HOSTS in Django, config.hosts in Rails, the TrustHosts middleware in Laravel and AllowedHosts in ASP.NET Core. PortSwigger's advice for the layer in front, given to prevent routing-based attacks on internal infrastructure, is to configure the load balancer or any reverse proxies to forward requests only to a whitelist of permitted domains.
This page's advice is to enforce the same list of names at the proxy, so that a request for an unknown name is answered there and never reaches the application.
- A wildcard switches the check off. Django says a value of '*' makes you responsible for your own validation of the Host header, and ASP.NET Core says a wildcard entry allows all non-empty Host header values even if other entries are present.
- A pattern has to cover the whole name. Rails wraps a regular expression entry with both anchors so that it must match the entire hostname. Laravel treats each hostname string as a regular expression, and its example value begins with ^ and ends with $.
- The list covers only code that goes through it. Django says code that accesses the Host header directly from request.META bypasses the protection.
- Subdomains follow each framework's own rule. In Django an entry beginning with a period is a subdomain wildcard, in Rails an entry such as .product.com permits the domain and all sub-domains, and Laravel 13.x trusts subdomains of the application's URL by default unless the subdomains argument turns that off.
On a web server that picks a site by name, decide what answers when no name matches. Left alone, nginx and Apache 2.4 give that job to the first server or virtual host listed, as their documentation says above.
Put a site that serves nothing in that position. The nginx documentation shows the building block, a server that returns 444 and closes the connection, and Django's checklist shows it as a default server for unrecognised hosts.
Whichever header your application reads the public name from, the proxy directly in front of it should write that header on every request, replacing any value that arrived from outside, and remove the alternatives it does not use. Express's guide to running behind proxies attaches a warning to its own setting: when trust proxy is set to true, it is important to ensure that the last reverse proxy trusted is removing or overwriting all of X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto, otherwise it may be possible for the client to provide any value. nginx documents both operations: proxy_set_header redefines a field of the request header passed to the proxied server, and a field whose value is set to an empty string is not passed at all.
Then turn on the framework's forwarded-header support only where a proxy sets the header, which is the condition Django attaches to USE_X_FORWARDED_HOST, and name the proxies it may come from, as Laravel's TrustProxies middleware and ASP.NET Core's known proxies do.
In case 4B the careful proxy wrote X-Forwarded-Host from the Host header it had just checked, and the application received bookings.tideline.example in that header instead of the name the client sent.
A refusal has three properties, whatever status it uses. It is a plain error and not a page of the site. Nothing in it is built from the name that was sent. And it happens before the request reaches code that sends a message or stores a response.
PortSwigger gives two acceptable answers for an unrecognised host, rejecting the request or redirecting it. If you redirect, send the browser to the configured origin, never to an address built from the request.
The products on this page choose different statuses. Django's documentation leads to a 400. Rails 8.1 answers 403 Forbidden by default. The nginx examples return 444, the non-standard code that closes the connection. RFC 9110 defines 421 (Misdirected Request) for a target URI that does not match an origin for which the server has been configured, with one restriction: a proxy MUST NOT generate a 421 response.
Section 3.7 uses proxy for a message-forwarding agent chosen by the client and gateway for a reverse proxy, and section 15.5.20 names a gateway acting on behalf of the origin server among the senders of 421.
The lab's careful application and reverse proxy both answer 421 with one fixed sentence. Choosing 421 over the others is this page's decision for the lab and not a rule.
Host header testing, one layer at a time
The test pack on this page has four rows: absolute URL generation, password reset links, cache variation and proxy forwarding.
Each row is a request to send to your own application, something to observe, and the result to expect once the controls are in place. The WSTG test puts the starting point in one line: initial testing is as simple as supplying another domain into the Host header field, and it is how the web server processes the header value that dictates the impact.
Keep the testing inside these limits. Use a staging or test copy of an application you own or are authorised in writing to test. Use a test account whose mailbox you control, because two of the rows cause a reset message to be sent, and do not request a reset for a real person's account.
Use an invented name for the other host: the lab uses one under .test, one of the four top level names RFC 2606 reserves. Do not use a real domain you do not control, because a link built from it would point at someone else's site.
And run the cache row only on a path no visitor uses, because a test that succeeds stores a response that later visitors are served.
- The application alone. If you can reach the application without the proxy, on a developer machine or inside the staging network, send rows 1 and 2 straight to it. This shows what the framework does when nothing in front has filtered the request.
- The proxy. Send a request for an unknown name through the proxy to a path that exists and note which layer answered: the status, the body and any header that identifies the server. Then send the real name with your own X-Forwarded-Host header, and have the application log the Host and forwarded host headers it received for that one request.
- The cache. On a test-only path, request the page with the other name, then with the real name, and read the cache status header your product returns. Then read how the cache key is defined.
- The whole chain. Repeat all four rows through the public address of the test environment, which is the route a request from outside takes.
- The header rules. Send one request with no Host header and one with two. RFC 9112 section 3.2 says a server MUST respond with a 400 (Bad Request) status code to any HTTP/1.1 request message that lacks a Host header field, and to any request message that contains more than one Host header field line.
- The other forwarded headers. Repeat row 4 with each header your framework or proxy documents, including Forwarded with a host parameter.
Reading the cache key
RFC 9111 section 2 says a cache key is composed from, at a minimum, the request method and target URI. RFC 9112 section 3.3 says that when the request-target is in neither absolute-form nor authority-form, the target URI's authority component is the field value of the Host header field.
On this page's reading, a cache keyed on the whole target URI therefore keeps names apart. Products and configurations vary. Cloudflare's documentation lists the full URL, with scheme and host, and the x-forwarded-host header in its default cache key. nginx's documented default key is the scheme, the proxied host and the request URI, and its documentation defines the proxied host as the name and port of a proxied server as specified in the proxy_pass directive.
On this page's reading, that is not the Host header the client sent.
PortSwigger says standalone caches typically include the Host header in the cache key, so poisoning through the Host header usually works best on integrated, application-level caches. Read the key your own cache uses, including any cache inside the application.
Read the evidence, not the status
A row passes when the origin in what the application generated is the configured one, or the request was refused. A 200 with the right page proves nothing until you have read the links in it. For the two reset rows the evidence is the message that arrived in the test mailbox, or the fact that none did.
Keep each request, its response and the date, because that record is what shows which origin was in use after the fix.
What these tests do not cover
This is a test of your own names against your own configuration. It does not exercise HTTP request smuggling, where two servers disagree about where a request ends and a second request, with a Host header of its own, rides inside the first: the HTTP request smuggling guide covers that.
And it does not find hostnames that point at services you no longer hold, which is the subject of the subdomain takeover guide.
Running the trusted-host lab
The lab on this page is an illustration.
It is an invented booking application, Tideline Tours, with a small reverse proxy and a small cache written for the lab, all held in memory and all listening on 127.0.0.1. It shows the pattern this page describes. It does not show how any real framework, proxy or CDN behaves. The application sends no email: a reset message is an entry in an in-memory outbox, which the lab prints.
Each of the three parts has a careless and a careful version. The careless application builds links from the request, preferring X-Forwarded-Host to Host. The careless proxy passes a client's X-Forwarded-Host on. The careless cache's key is the method and the request's URL, which in every lab request is a path with no query string.
The careful application builds every link from one configured origin, https://bookings.tideline.example, and answers 421 to any Host header that is not one of its two served names.
The careful proxy refuses unknown names itself and replaces X-Forwarded-Host with the name it checked. The careful cache adds the Host header to its key. Every name in the lab is invented and sits under .example or .test.
The lab client opens each connection to the literal address 127.0.0.1 and writes the request as text, with the Host header set in the request itself. It sends its three host names only as header values and never connects to one.
Apart from each other, the lab files import only node:assert/strict, node:http, node:net and node:test, and the lab installs no packages. Each server asks for port 0. Node.js's documentation says the HTTP server's listen() is identical to the one in its net module, where port 0 makes the operating system assign an arbitrary unused port.
The recorded run was made on Node.js 26.0.0 on macOS, the only version and the only system it was run on.
- Case 1A, a page requested with Host: other-host.test. Careless: status 200, and the links on the page begin with https://other-host.test. Careful: status 421 and no link.
- Case 1B, the same page requested through the second served name, tideline-tours.example. Careless: the links begin with https://tideline-tours.example. Careful: they begin with the configured origin.
- Cases 2A and 2B, a reset request with the same two Host headers. Careless: the outbox holds a message whose link begins with the name the request sent. Careful: status 421 and an empty outbox for the unknown name, and a link to the configured origin for the served one.
- Case 3, three requests for one page through the cache. Careless: the first, for other-host.test, is stored under the key GET /tours/sunrise-paddle, and the next two requests, which sent served names, are answered from the cache with that page. Careful: the first is refused and nothing is stored, the other two are stored under separate keys, and both stored pages link to the configured origin.
- Case 4A, a reset request through the proxy with an unknown Host header. Careless: it reaches the application and produces a link to the other name. Careful: the proxy answers 421 and the application receives nothing.
- Case 4B, the served Host header with X-Forwarded-Host: other-host.test. Careless: the application received both headers as the client sent them and wrote a link to https://other-host.test. Careful: the application received X-Forwarded-Host: bookings.tideline.example, and the link carries the configured origin.
The regression tests
The file trusted-host.test.mjs holds one test for each case, written as a statement of what the careful version does. Run against the careless version, all seven fail. Run against the careful version, all seven pass. Node.js's documentation says that if any tests fail, the process exit code is set to 1, and the two recorded runs ended with exit codes 1 and 0. A release pipeline can use that difference to stop a release.
To use the tests on your own application, keep the assertions and replace the lab client with requests to your staging address and a read of your test mailbox. The assertion worth keeping is the same in every row: the origin in whatever was generated is the configured one, or the request was refused.
Where a Clever Ops test fits
One neighbouring guide has not come up yet.
The security misconfiguration guide covers settings that differ between the environment a team tested and the one that is live, which is how a host list that is right on staging can be missing in production.
A Clever Ops web application and API penetration test covers authentication and sessions, what each role can see and change, and the API called directly rather than only through the screens. Read-only code access to named areas can be added to the scope, and a finding that rests on the code alone says so.
Lockout and reset checks run only on test accounts, where the rules of engagement allow them, and no password reset is triggered for a real person's account.
A CDN, load balancer or proxy in front of the application may be run by another business and may have testing terms of its own. When you book a scoping call, say which CDN or reverse proxy sits in front of the application, who controls its settings, and whether a staging copy runs behind the same configuration.
If you want host handling at those layers considered, raise it on the call, so that it is either in the written scope or listed as an exclusion.
Laravel applications sit outside this service. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
It is a weakness in which an application takes its own name from the request, from the Host header or a forwarded copy such as X-Forwarded-Host, and uses it to build a link, a redirect or a cached page. Because the sender of a request writes those headers, the sender chooses the name. OWASP's Web Security Testing Guide v4.2 tests for it as WSTG-INPV-17 and lists four outcomes: requests dispatched to the first virtual host on the list, a redirect to an attacker-controlled domain, web cache poisoning and manipulated password reset functionality.
The two names are used for the same family of problems. PortSwigger's Web Security Academy uses HTTP Host header attacks as the general name for attacks on websites that handle the value of the Host header in an unsafe way, and says those that inject a payload directly into the header are often known as Host header injection attacks. OWASP's testing guide uses the second name for its test.
PortSwigger defines it as a technique whereby an attacker manipulates a vulnerable website into generating a password reset link pointing to a domain under their control. The website sends a genuine email with a valid token, but the link leads to the attacker's server, which receives the token if the link is opened. OWASP's Forgot Password Cheat Sheet gives the fix: do not rely on the Host header while creating reset URLs, and hard-code the URL or validate it against a list of trusted domains.
It closes one door. A list such as Django's ALLOWED_HOSTS refuses names you do not serve, but in the lab the careless application still wrote links to its own second served name, which a list holding that name accepts. Django's documentation adds that its check only applies through get_host(), so code that reads the header directly bypasses it. Build links from one configured origin as well, and have the proxy in front overwrite forwarded host headers.
Only when a proxy you control writes it on every request. RFC 7239 says of the standard Forwarded header that it cannot be relied upon to be correct, because every node on the way to the server may modify it, including the client making the request. Express's guide to running behind proxies warns that with trust proxy set to true, it is important to ensure that the last reverse proxy trusted is removing or overwriting all of X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto, otherwise it may be possible for the client to provide any value. Django 6.1 leaves its support for the header off by default (USE_X_FORWARDED_HOST defaults to False in its settings reference) and says to enable it only if a proxy which sets this header is in use.
The products on this page differ. Django's documentation leads to a 400 response, Rails 8.1 answers 403 Forbidden by default, and the nginx examples return 444, a non-standard code that closes the connection. RFC 9110 defines 421 (Misdirected Request) for a request whose target does not match an origin the server has been configured for. The number matters less than the timing and the content: the refusal comes before any link is built, message is sent or response is stored, and nothing in it is built from the name that was sent.
Test your own application in a staging or test environment, with a test account whose mailbox you control and an invented name for the other host. Send a request with that name in the Host header, then one with your real name and an X-Forwarded-Host header, and read the origin in whatever was generated: the page, the redirect and the reset message. Run the cache check only on a path no visitor uses. The four-row test pack on this page sets out each request and the result to expect.
It can keep cached pages for different names apart, and it leaves the links your application writes as they were. Cloudflare's documentation, for example, lists the full URL, with its host, and the x-forwarded-host header in its default cache key. On this page's reading, that separates what that cache stores for one name from what it stores for another. A reset email is not a cached response, so no cache key changes the link inside it.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.