# WEB13: Web Cache Poisoning
## Lab: Web cache poisoning with an unkeyed header
```!
This lab is vulnerable to web cache poisoning because it handles input from an unkeyed header in an unsafe way. An unsuspecting user regularly visits the site's home page. To solve this lab, poison the cache with a response that executes alert(document.cookie) in the visitor's browser.
```
Thử gửi một request bất kì hai lần, ta thấy response header thay đổi như sau `X-Cache: miss` -> `X-Cache: hit` => Server có sử dụng cache, và bên cạnh đó còn dựa vào request header `X-Forwarded-Host` để tạo ra các resource 1 cách tự động, như trong hình dưới thuộc tính `src` của tag `script` được thay đổi dựa trên header này.

Setup lại exploit server

Send request 2 lần để poison cache

Kết quả

## Lab: Web cache poisoning with an unkeyed cookie
```!
This lab is vulnerable to web cache poisoning because cookies aren't included in the cache key. An unsuspecting user regularly visits the site's home page. To solve this lab, poison the cache with a response that executes alert(1) in the visitor's browser.
```
Ta thấy cookie `fehost` được refect trong field `frontend` của biến `data`.

Thử break tag script và xss:

kết quả:

Chỉnh request line lại thành `GET /` và send request 2 lần

Solve bài lab

## Lab: Web cache poisoning with multiple headers
```!
This lab contains a web cache poisoning vulnerability that is only exploitable when you use multiple headers to craft a malicious request. A user visits the home page roughly once a minute. To solve this lab, poison the cache with a response that executes alert(document.cookie) in the visitor's browser.
```
Ban đầu thử set giá trị bất kì cho header `X-Forwarded-Host` thì nhận thấy k có sự thay đổi nào trong respone.
Sau một hồi fuzzing, phát hiện ra nếu set giá trị cho h`X-Forwarded-Scheme` là `http` thì server response với status 302 đến trang https

Và nếu ta set hai giá trị này đồng thời đối với request line là `/resources/js/tracking.js` thì

-> XSS thành công và solve bài lab


## Lab: Targeted web cache poisoning using an unknown header
```!
This lab is vulnerable to web cache poisoning. A victim user will view any comments that you post. To solve this lab, you need to poison the cache with a response that executes alert(document.cookie) in the visitor's browser. However, you also need to make sure that the response is served to the specific subset of users to which the intended victim belongs.
```
Trong trang comment, view source ta thấy có sử dụng domPurify để sanitize html input tuy nhiên version này khá cũ

Và từ post [này](https://portswigger.net/research/bypassing-dompurify-again-with-mutation-xss) có thể bypass bằng payload sau:
```
<math><mtext><table><mglyph><style><!--</style><img title="--><img src=1 onerror=alert(1)>">
```
Kết quả:

Dựa theo yêu cầu bài lab, tiếp đến ta cần tìm User-Agent của victim => XSS redirect đến exploit server và check Access log

Chỉnh lại payload XSS alert(document.domain) theo như yêu cầu

Poisoning cache attack các request với user-agent của victim:

Kết quả:

## Lab: Web cache poisoning via an unkeyed query string
```!
This lab is vulnerable to web cache poisoning because the query string is unkeyed. A user regularly visits this site's home page using Chrome.
To solve the lab, poison the home page with a response that executes alert(1) in the victim's browser.
```


Từ hai hình trên có thể thấy toàn bộ query string của ta bị exclude và không được coi là cache key, nhưng response vẫn bao gồm chúng vì vậy có thể khai thác bằng cách chờ response trong cache expire và poison cache với payload xss thông qua query string

Solve bài lab

## Lab: Web cache poisoning via an unkeyed query parameter
```!
This lab is vulnerable to web cache poisoning because it excludes a certain parameter from the cache key. A user regularly visits this site's home page using Chrome.
To solve the lab, poison the cache with a response that executes alert(1) in the victim's browser.
```
Dùng header `Pragma: x-get-cache-key`, ta thấy cache key bao gồm các query parameter

Tuy nhiên đối với param `utm_content` thì lại không được đưa vào cache key

Và một điều quan trọng nữa đó là query string sẽ được reflect hoàn toàn vào response:

Vậy chỉnh lại query string và exploit thôi

kết quả

## Lab: Parameter cloaking
```!
This lab is vulnerable to web cache poisoning because it excludes a certain parameter from the cache key. There is also inconsistent parameter parsing between the cache and the back-end. A user regularly visits this site's home page using Chrome.
To solve the lab, use the parameter cloaking technique to poison the cache with a response that executes alert(1) in the victim's browser.
```


Từ hai hình trên có thể thấy được các param sẽ được include trong cache key ngoại trừ utm_content
Tiếp theo, dựa vào lí thuyết ta send request sau

```
?callback=setCountryCookie&utm_content=123;callback=alert(1)//
```
- cache server sẽ thấy chỉ có một cache key là `/js/geolocate.js?callback=setCountryCookie$$` (xem `utm_content=...` như một param cần được exclude)
- tuy nhiên bên phía backend (maybe xài rails) parse query string và thấy có tới tận 3 param `callback`, `utm_content` và `callback` -> chỉ giá trị của `callback` cuối cùng được lấy
Kết quả

## Lab: Web cache poisoning via a fat GET request
```!
This lab is vulnerable to web cache poisoning. It accepts GET requests that have a body, but does not include the body in the cache key. A user regularly visits this site's home page using Chrome.
To solve the lab, poison the cache with a response that executes alert(1) in the victim's browser.
```
Vẫn ở endpoint JSONP cũ, ta thử thêm body cho GET request như sau và nhận thấy, body k được đưa vào cache key và đồng thời server sử dụng giá trị trong body để trả về response:

Solve

## Lab: URL normalization
```!
This lab contains an XSS vulnerability that is not directly exploitable due to browser URL-encoding.
To solve the lab, take advantage of the cache's normalization process to exploit this vulnerability. Find the XSS vulnerability and inject a payload that will execute alert(1) in the victim's browser. Then, deliver the malicious URL to the victim.
```
Thử truy cập đến đường dẫn không tồn tại trên server

-> Có thể khai thác xss ở đây.
Đề bài cho ta gửi link đến victim, tuy nhiên nếu chỉ đơn thuần gửi gửi link là `https://0a7300b70472dc6bc2770dc3005b005d.web-security-academy.net/abcd<script>alert(1)</script>` thì sẽ chỉ nhận lại chuỗi đã bị url encode bởi trình duyệt:

Vì vậy ta cần lợi dụng cơ chế normalize cache key của cache server. Poison cache với burp repeater

Và sau đó XSS bằng browser

Kết quả

## Lab: Cache key injection
```!
This lab contains multiple independent vulnerabilities, including cache key injection. A user regularly visits this site's home page using Chrome.
To solve the lab, combine the vulnerabilities to execute alert(1) in the victim's browser. Note that you will need to make use of the Pragma: x-get-cache-key header in order to solve this lab.
```
`GET /login?lang=en` sẽ redirect đến `/login/?lang=en`

Và ở request này, ta thấy server import file js với `src='/js/localize.js?lang=en&cors=0'`

Và request ở `GET /login?lang=en` + `GET /js/localize.js?lang=en&cors=0` đều được cache
Bên cạnh đó `Origin` header cũng nằm trong cache key, và ta có thể inject vào header này để chỉnh response trả về nếu `cors=1`

Poison cache và sau đó gửi một request line như sau để lấy response lưu trong cache

Vậy việc còn lại chỉ là cần làm cho thuộc tính `src` của `script` trỏ đến `/js/localize.js?lang=en&cors=1&x=bla$$origin=x%0d%0aContent-Length:%208%0d%0a%0d%0aalert(1)$$`
Tiếp tục fuzzing, ta thấy `utm_content` vẫn sẽ không được include vào cache key

Vậy ta chỉnh lại injected cache key để tí nữa có thể poinson cache ở `GET /login?lang=en`


Poin cache ở `/loign`, ở đây cần dùng `?utm_content` bởi vì server chỉ lấy param `lang` từ request và nhét vào thuộc tính `src` ở dạng `<lang_param_value>&cors=0`, nên nếu bỏ đi trường này thì request line sẽ bị cắt bỏ.

(`%23` ở cuối để "cắt" đi `&cors=0` - [HTTP parameter pollution](https://owasp.org/www-pdf-archive/AppsecEU09_CarettoniDiPaola_v0.8.pdf) )
Kết quả

## Lab: Internal cache poisoning
```!
This lab is vulnerable to web cache poisoning. It uses multiple layers of caching. A user regularly visits this site's home page using Chrome.
To solve the lab, poison the internal cache so that the home page executes alert(document.cookie) in the victim's browser.
```
Dùng param miner, ta tìm được header `X-Forwared-Host` là đặc biệt

Ở đây để ý nếu ta send `GET /` thì giá trị của header được reflect trong response - khi fetch `analytis.js` tuy nhiên đối với `geolocate.js` thì vẫn giữ nguyên => chúng được cache bởi hai fragment khác nhau.
Tiếp tục send request, lúc này đã thành công thay đổi được hostname ứng với `geolocate.js`

Thử bỏ đi header này và send lại request

-> Rút ra kết luận rằng `X-Forwared-Host` là một keyed input đối với external cache, nhưng lại là một unkeyed input đối với internal cache.
Setup exploit server

Kết quả

## Lab: Web cache poisoning to exploit a DOM vulnerability via a cache with strict cacheability criteria
```!
This lab contains a DOM-based vulnerability that can be exploited as part of a web cache poisoning attack. A user visits the home page roughly once a minute. Note that the cache used by this lab has stricter criteria for deciding which responses are cacheable, so you will need to study the cache behavior closely.
To solve the lab, poison the cache with a response that executes alert(document.cookie) in the visitor's browser.
```
Ta thấy ở trang home có gọi hàm initGeoLocate với tham số thứ nhất được concat bởi data.hót

Nội dung hàm này như sau: fetch đến jsonUrl, lấy response -> parse json và đưa vào `innerHTML` của thẻ div để render => sink DOM based XSS tại đây

Poison giá trị của host trong `data` thành exploit server

Setup exploit server

kết quả

## Lab: Combining web cache poisoning vulnerabilities
```!
This lab is susceptible to web cache poisoning, but only if you construct a complex exploit chain.
A user visits the home page roughly once a minute and their language is set to English. To solve this lab, poison the cache with a response that executes alert(document.cookie) in the visitor's browser.
```
Request tại home page như sau:

Ta thấy về mặt logic thì vẫn tương tự như bài lab trước.
Trường Cookie được dùng để chỉ định language của trang web và sử dụng hàm `initTranslations` để translate
Hàm này được định nghĩa như sau:
```js=
function initTranslations(jsonUrl)
{
const lang = document.cookie.split(';')
.map(c => c.trim().split('='))
.filter(p => p[0] === 'lang')
.map(p => p[1])
.find(() => true);
const translate = (dict, el) => {
for (const k in dict) {
if (el.innerHTML === k) {
el.innerHTML = dict[k];
} else {
el.childNodes.forEach(el_ => translate(dict, el_));
}
}
}
fetch(jsonUrl)
.then(r => r.json())
.then(j => {
const select = document.getElementById('lang-select');
if (select) {
for (const code in j) {
const name = j[code].name;
const el = document.createElement("option");
el.setAttribute("value", code);
el.innerText = name;
select.appendChild(el);
if (code === lang) {
select.selectedIndex = select.childElementCount - 1;
}
}
}
lang in j && lang.toLowerCase() !== 'en' && j[lang].translations && translate(j[lang].translations, document.getElementsByClassName('maincontainer')[0]);
});
}
```
Và file json:

Cookie language được set thông qua endpoint `GET /setlang/en?` và có thể rewrite bằng `X-Original-Url`

Vậy ý tưởng sẽ là poison cache ở `GET /` thành `GET /setlang/es`, lúc này victim access đến home page sẽ bị redirect đến `/?localized=1`, và tiếp tục poison `GET /?localized=1` với `X-Forwarded-Host` để trỏ đến exploit server.
Setup exploit server

*(Vì trong đoạn mã js trên ta cần `lang` phải khác `en` => có thể dùng `es`)*
Poison `GET /` thành `GET /setlang/es`

vì response bao gồm set-cookie header [nên](https://cdnsun.com/knowledgebase/cdn-static/setting-a-set-cookie-ignore-or-accept) response này không được cache, thay vào đó ta có thể làm như sau

*(chỉnh giá trị của `X-Original-Url` lại thành `/setlang\es` -> redirect đến `/setlang/es`)*
Poison `GET ?localized=1`

Solve bài lab

###### tags: `portswigger`