何为"污染画布(tainted canvas)"风险?其具体攻击原理是什么?
You hit exactly the scenario this protection is built to stop—let's walk through every step of how this attack would unfold if there were no canvas taint rules:
User visits nastysite.com
You open the malicious site in your browser, which loads a hidden script in the background. Since you might have logged into mybankingsite.com or mydatingsite.com earlier, your browser still holds active cookies for those domains.Malicious script loads a sensitive cross-domain image
The script creates an invisible<img>element and sets itssrcto a URL from your bank or dating site—say,https://mybankingsite.com/user/account-summary.png. Because your browser sends your bank's cookies along with this request, the bank's server thinks it's a legitimate request from you and returns the image with your account balance, recent transactions, or other private details.Image is drawn to a hidden canvas
The script then creates a hidden<canvas>element (you'll never see it on the page) and uses Canvas API to draw the sensitive image onto it:// Example malicious code snippet const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const sensitiveImg = new Image(); sensitiveImg.src = 'https://mybankingsite.com/user/account-summary.png'; sensitiveImg.onload = () => { ctx.drawImage(sensitiveImg, 0, 0); // Image is now on the canvas—next step: extract data };Pixel data is extracted
Without canvas tainting, the script could callctx.getImageData(0, 0, canvas.width, canvas.height)to grab a raw array of every pixel's RGBA values from the canvas. It could then parse this data to read text (like your account balance) or convert the whole thing to a Base64 string that's easy to transmit.Stolen data is sent to the malicious server
Finally, the script usesfetch()orXMLHttpRequestto send the extracted pixel data back to nastysite.com's servers. The attackers now have your private information, all without you interacting with anything suspicious on the page.
How canvas tainting blocks this attack
Thankfully, browsers stop this exact flow cold: as soon as you draw a cross-origin image that doesn't allow cross-domain access onto a canvas, the canvas becomes "tainted." Any attempt to call getImageData(), toDataURL(), or other data-reading APIs will throw a SecurityError, preventing the attacker from stealing that sensitive pixel data.
内容的提问来源于stack exchange,提问作者M Katz

