Отравление кэша и защита слоя кэширования
Узнайте, как работают атаки с отравлением и подменой кэша и как усилить слой кэширования против них, тщательно обрабатывая ключи и заголовки.
«Отравление кэша и защита слоя кэширования» — бесплатный урок Caching Strategies: Redis + CDN + Edge Computing на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Caching Strategies: Redis + CDN + Edge Computing, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Caching Strategies: Redis + CDN + Edge Computing содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
What Is Cache Poisoning?
Web cache poisoning tricks a cache into storing a malicious response that is then served to other users. The attacker manipulates an input that influences the response but is not part of the cache key.
- Attacker sends a crafted request
- Origin reflects attacker input into the response
- Cache stores it and serves it to everyone
Unkeyed Inputs Are the Risk
The root cause is an unkeyed input: a header or parameter that changes the response but is excluded from the cache key. If an attacker controls it, they poison the shared entry.
Example: Poisoning via a Custom Header
Imagine the origin reflects X-Forwarded-Host into a generated URL but the cache ignores that header. An attacker sets it to their domain, and the cached page now points everyone at attacker resources.
GET / HTTP/1.1
Host: example.com
X-Forwarded-Host: evil.comCache Key Hygiene
The primary defense is to include every input that affects the response in the cache key, or to strip dangerous headers before caching. Never reflect untrusted headers into cached output.
Cache Deception
Cache deception tricks the cache into storing private data under a public-looking URL. An attacker appends a fake static extension so the cache treats a sensitive page as a cacheable asset.
https://app.com/account/info.css (still serves the private account page)Defending Against Deception
Defend by caching based on the actual Content-Type and explicit rules, not just the URL extension. Never cache responses marked private or that set authenticated cookies.
Stripping Risky Headers
Configure the edge to drop headers an attacker should not control before they reach the origin or cache, such as forwarded-host style headers unless explicitly trusted.
proxy_set_header X-Forwarded-Host "";Sanitizing Reflected Values
If the origin must echo a value, validate and encode it. Never build cacheable URLs or scripts directly from request headers without strict allow-lists.
Separating Authenticated Traffic
Authenticated responses should generally bypass shared caches. Route logged-in requests around the public cache, or mark them private, no-store so they are never shared.
Cache-Control: private, no-storeMonitoring for Poisoning
Watch for anomalies: sudden cache entries with unexpected hosts, spikes in 4xx after a deploy, or reports of users seeing foreign content. Detection lets you purge fast.
Hardening Checklist
Protect the cache layer by:
- Keying on every response-affecting input
- Stripping untrusted forwarding headers
- Caching by content type, not URL extension
- Never caching private or authenticated responses
- Encoding any reflected request values
Quick Check
Test your cache security understanding.
Recap
You learned how cache poisoning and cache deception attacks exploit unkeyed inputs and URL-based caching. You saw defenses: rigorous cache-key hygiene, stripping untrusted headers, caching by content type, never sharing authenticated responses, and monitoring for anomalies.
Часто задаваемые вопросы
Урок «Отравление кэша и защита слоя кэширования» бесплатный?
Да — полный текст урока «Отравление кэша и защита слоя кэширования» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Caching Strategies: Redis + CDN + Edge Computing, подпишись на CoddyKit PRO. Курс Caching Strategies: Redis + CDN + Edge Computing содержит 4 уроков всего.
Чему я научусь в уроке «Отравление кэша и защита слоя кэширования»?
Узнайте, как работают атаки с отравлением и подменой кэша и как усилить слой кэширования против них, тщательно обрабатывая ключи и заголовки. Ты практикуешь Caching Strategies: Redis + CDN + Edge Computing с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Caching Strategies: Redis + CDN + Edge Computing?
Предыдущий опыт не требуется. Caching Strategies: Redis + CDN + Edge Computing на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Отравление кэша и защита слоя кэширования»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Caching Strategies: Redis + CDN + Edge Computing?
Да. Каждый урок Caching Strategies: Redis + CDN + Edge Computing включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Резервные варианты кэша и Circuit Breaker
- Лучшие практики безопасности кэшей
- Будущие тенденции кэширования
- Отравление кэша и защита слоя кэширования